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.
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: For instructions on enabling the IIS6 or IIS7 Classic mode,
// Please visit 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} // default value of the Parameter
);
}
// 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, the default value is Home. The second part is called the Action method. If not provided, the default value is Index. The third part is called id, which is usually used to provide the data identifier without the 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.
Added HomeController
Our App Store starts from adding a Controller for the homepage and uses the default naming convention. The Controller name should be suffixed with Controller. We name this Controller HomeController.
Right-click the Controller folder and select "add" and "Controller (T )..."
In the displayed dialog box, enter the Controller name HomeController and press "add.
In this way, a file named HomeController. cs will be created, and the code is as follows:
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Web;
Using System. Web. Mvc;
Namespace MvcMusinStore. Controllers
{
Public class HomeController: Controller
{
//
// GET:/Home/
Public ActionResult Index ()
{
Return View ();
}
}
} To make it as simple as possible, let the Index method simply return a string, which will return the browser directly as the response content. Let's make the following two simple modifications.
- Change the return type of the method to string.
- Change the return statement to return "Hello form Home ";
In this way, our method will become the following content:
public string Index(){ return "Hello form Home";}
Run the program
Now, you can run it. We can start the server and use any of the following methods.
- Select "debug" and "start debugging ".
- Click the green arrow on the toolbar.
- Use keyboard shortcuts, F5
Any of the above methods will cause compilation of the project and start the built-in ASP. NET development server in Visual Studio.
In the lower-right corner of the screen, a prompt is displayed to start the ASP. NET development server,
Visual Studio automatically opens a browser window with the address pointing to our Web server, which allows us to quickly use our program.
OK, it's very simple. We have created a Web site and written a three-line function. It's not shocking to get this line of text in the browser, but it's just the beginning.
Added StoreController
We have added a simple HomeController as the homepage for the website. Now, we have added another 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, we can stop the program just now. You can directly close the browser, or choose to stop debugging from the debugging menu.
Now, add a new StoreController. Just as in HomeController, 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. As you can see earlier, the Index method in HomeController is an Action, and these actions are used to process requests, then return the request processing result.
For our StoreController, first let the Index Action return a "Hello" string, and then add two methods: Browse () and Detials ()
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Web;
Using System. Web. Mvc;
Namespace MvcMusinStore. Controllers
{
Public class StoreController: Controller
{
//
// GET:/Store/
Public string Index ()
{
Return "Hello from Store. Index ()";
}
Public string Browse ()
{
Return "Hello from Store. Browse ()";
}
Public string Details ()
{
Return "Hello from Store. Details ()";
}
}
}
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/5public 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.
From champion