I. Role of Controllers
In the MVC mode, the Controller is responsible for responding to user input and processing data based on user input. The Controller is related to the application process. It processes the incoming data and provides the data to the relevant view.
In traditional web programs, URLs usually correspond to files on the server's hard disk. In MVC, URLs correspond to controller methods. MVC relies on method calls to generate results, rather than dynamic page generation.
2. Create the first Controller
1. Create a controller
In Solution ExplorerControllersRight-click the folder and choose add> controller.
Enter the Controller name
2. Create an Action
Add the following code to the Controller:
Public string Index () {return "Hello Store. Index ()! ";} Public string Browse () {return" Hello Store. Browse ()! ";} Public string Details () {return" Hello Store. Details ()! ";}
3. action Parameters
Add a string parameter named "genre" to Browse action.
public string Browse(string genre) { string message = HttpUtility.HtmlEncode("Store.Browse, Genre =" + genre); return message; }
HttpUtility. HtmlEncode is used to encode user input and prevent users from injecting JavaScript scripts or html tags, such as entering/Store/Browse in a browser? Genre = <script> window. location = 'HTTP: // hacker.example.com '</script>.
Modify the Details action to read and display the user input id
public string Details(int id) { string message = "Store.Details, ID=" + id; return message; }
Summary:The Controller is the manager of MVC applications. It closely associates users, model objects, and views. It responds to user input, controls model objects, and selects the correct view for user input.