1. Introduction
MVC consists of three parts: model, view, and controller. First, let's take a simple look at controller and take musicstore as an instance. First, let's have a preliminary impression.
2. Introduction to music store
Musicstore is a good learning instance and provides detailed operation steps. : Http://mvcmusicstore.codeplex.com/
It is a simple music store, mainly including three functional modules: shopping, settlement and background management.
First open the full version and check the running effect:
3. Create a music store project
Start from scratch and build our music store step by step.
Create a project and set options, as shown in:
- L Project template-> empty
- L view engine-> razor
- L user HTML5 semantic markup-> selected
Click OK to view the solution and find that the corresponding folder has been created.
4. Controller
During web form development, the URL in the website often corresponds to the disk directory where the webpage file is located. For example, www.buy.com/products.aspxcan correspond to the file named products.aspxunder a specific directory. But in MVC, the URL does not correspond to a specific file, but to the Controller Action Method in the Controller class. It processes HTML requests, operates user input, reads and writes data, and determines the client response (such as displaying HTML, displaying files, page jumps, etc ).
① Add homecontroller: Right-click contoller-> Add-> Controller
We can see the generated homecontrollerCodeAs follows:
Namespace musicstore. Controllers
{
Public class homecontroller: Controller
{
//
// Get:/home/
Public actionresult index ()
{
Return view ();
}
}
}
Modify index () as follows:
Running effect:
② Add store storecontroller and add three methods to respond to URL requests:
Public class storecontroller: Controller
{
Public String index ()
{
Return "hello from store. Index ()";
}
Public String browse (string genre)
{
String strmsg = httputility. htmlencode ("store. Browse, genre =" + genre );
Return strmsg;
}
Public String details (int id)
{
String strmsg = "store. Details, id =" + ID;
Return strmsg;
}
}
③ Running effect:
- The method for passing parameters in the Browse method is easy to understand. It is the same as that in webform development 【? Key = Value]
- The format of passing parameters in the details () method is special, because when the parameters following the actionmethod in the URL are processed in MVC, the corresponding parameter name is "ID" by default ".