Controller is one of the three core elements in the MVC pattern.
The controller in the MVC pattern is primarily responsible for responding to the user's input and modifying the model when responding.
MVC provides the result of a method call, rather than a dynamically generated page.
The following is a new project named MVC Music Store, which illustrates the controller in MVC as an example.
1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.Linq;4 usingsystem.web;5 usingSYSTEM.WEB.MVC;6 7 namespacemvcmusicstore.controllers8 {9 Public classHomecontroller:controllerTen { One A Publicactionresult Index () - {
//Modify the default content to "I like cake!" to be displayed directly on the home page. viewbag.message = "I like cake! " ; the returnView (); - } - - PublicActionResult About () + { -Viewbag.message ="Your App description page."; + A returnView (); at } - - Publicactionresult Contact () - { -Viewbag.message ="Your Contact page."; - in returnView (); - } to } +}
The index method of the HomeController class determines the events that are triggered when the homepage of the site is browsed.
Next, create a new controller and name it Storecontroller, with the following modifications:
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingsystem.web;usingSYSTEM.WEB.MVC;namespacemvcmusicstore.controllers{ Public classStorecontroller:controller {// //GET:/store/ Public stringIndex () { return "Hello from Store.index ()" ; } //Get:/store/browse Public stringBrowse (stringgenre) {return "Hello from Store.browse ()"; } Public stringDetails () { return "Hello from Store.details ()" ; } }}
No additional configuration is required, and browsing to/store/details can execute the details method in the Storecontroller class, which is the route in action.
The only way to determine if a class is a Controller is to see if the class inherits from System.Web.Mvc.Controller.
Controoller is the real core of MVC, and every request must be handled by the controller. Some requests are not required for model and view.
Public string Browse (string genre) { string message = Httputility.htmlencode (" " + genre); return message; }
Use Httputility.htmlencode to preprocess user input. This prevents users from injecting JavaScript code or HTML markup into the view with links.
The controller can accept the query string as a parameter to its action method.
The default routing convention for ASP. NET MVC is to use this fragment of the URL following the action method name as a parameter with the name ID. If a parameter named ID is in the action method, then ASP. NET MVC automatically passes the URL fragment as an argument.