In a typical web application, the URL address requested by the user is usually mapped to a file stored in the website. For example, when the user requests/products. aspx, or/products. in PHP, it is likely that. aspx or products. PHP file to complete the task.
ASP. net MVC has different processing methods, which are not mapped to files. On the contrary, these URL addresses are mapped to class methods. These classes are called "controllers ", the controller is used to accept HTTP requests, process user input, and obtain or save data. The processing method is called action, and then sends the response to the client, which may be an HTML webpage, download an object and redirect it to another address.
1. Default route Configuration
Open the global. asax. CS file in the newly created project and you can see the following code.
Using system; using system. collections. generic; using system. LINQ; using system. web; using system. web. MVC; using system. web. routing; namespace mvcmusicstore {// Note: Instructions on enabling IIS6 or iis7 Classic mode, // visit the http://go.microsoft.com /? Linkid = 9394801 public class mvcapplication: system. web. httpapplication {public static void registerglobalfilters (globalfiltercollection filters) {filters. add (New handleerrorattribute ();} public static void registerroutes (routecollection routes) {routes. ignoreroute ("{resource }. axd/{* pathinfo} "); routes. maproute ("default", // route name "{controller}/{action}/{ID}", // URL with parameters new {controller = "home ", action = "Index", id = urlparameter. optional} // The default value of the parameter);} // It is generally used for website initialization protected void application_start () {system. data. entity. database. setinitializer (New mvcmusicstore. models. sampledata (); arearegistration. registerallareas (); registerglobalfilters (globalfilters. filters); registerroutes (routetable. routes );}}}
The registerroutes method registers the default route configuration. in the maproute statement, the request address is considered as a three-part structure, {controller}/{action}/{ID}. The first part is called the controller. If not provided, the default value isHomeThe second part is called the action method. If it is not provided, the default value isIndexThe third part is called the ID, which is usually used to provide the data identifier and has no default value. In this way, when the request/address is sent, the system maps the request to the Controller named Home for processing and calls the method named index to process the request.
2. Added storecontroller
Add a controller that can be used to browse our music store. Our store controller will support three scenarios:
- List the categories of records in a store
- Browse the list of records in a category in a store
- Display details of a specific record
Starting from adding a new storecontroller, right-click the controllers folder and select "add" and "controller ". The new storecontroller controller already contains the index method. We use this method to list all categories. We will add two additional methods to implement other scenarios: browsing and details.
These methods included in the controller are called the actions in the Controller. These actions are used to process the request and then return the processing result of the request.
For our storecontroller, first let the index action return a "hello" string, and then add two methods: browse () and detials ()
//// GET: /Store/Browse?genre=?Discopublic string Browse(string genre){ string message = HttpUtility.HtmlEncode("Store.Browse, Genre = " + genre); return message;}
Run the program again. Now you can access these addresses.
- /Store
- /Store/browse
- /Store/details
Great, but now we can only return some constant strings. Let's change them to dynamic. We get some information from the URL and display them in the returned page.
First, modify the Browse action so that it can obtain the query information from the URL address and add a string type parameter named "genre" to the method. When we do this, ASP. net MVC will automatically assign the value of any request parameter named genre to this parameter.
// // GET: /Store/Browse?genre=?Disco public string Browse(string genre) { string message = HttpUtility.HtmlEncode("Store.Browse, Genre = " + genre); return message; }
Note:
We use the httputility. htmlencode method to process user input, which can prevent script injection attacks. For example:/Store/browse? Genre = <SCRIPT> window. Location = 'HTTP: // hackersite.com '</SCRIPT>.
Now, visit/store/browse in the browser? Genre = disco
Next, we will process the details action so that it can process the integer type parameter named ID. This time, we will not pass this integer in the request parameter, but embed it in the request URL address. For example:/store/details/5.
In ASP. net MVC, we can easily complete this task without configuring anything, Asp. net MVC default routing Convention will regard the part after the action method as the value of the parameter named ID. If your action method has a parameter named ID, then ASP. net MVC will automatically send this part as a parameter to the action method. It should be noted that MVC can help you convert data types. Therefore, the third part of the address must be able to be converted to an integer.
// // GET: /Store/Details/5 public string Details(int id) { string message = "Store.Details, ID = " + id; return message; }
Run the program again to access/store/details/5
Summarize the tasks we have completed:
- Creates an ASP. net mvc project.
- Discussed basic project folders
- Learned how to run the Development Server
- Two controllers, homecontroller and storecontroller, are created.
- Added the Action Method to the Controller.
Music Store episode 3rd: Controller