Simple instances help you understand the routes and regions in MVC3 step by step, and mvc3 step by step

Source: Internet
Author: User

Simple instances help you understand the routes and regions in MVC3 step by step, and mvc3 step by step

We all know that all the requests of the MVC 3 program are first parsed by routes and then allocated to specific controllers and actions. Why do we need to talk about the Controller Action Model after learning this knowledge? I personally think this is more abstract! If you have a foundation, it seems a little effort-consuming. If you have no foundation, you don't even know what the Controller Action is, how do you understand routing? Hey, it's just my opinion! If you do not know some basic information about MVC 3, follow the instructions below to learn more about MVC 3 and then read this article. In the previous article, all the things that involve routing knowledge have a simple explanation of routing. For those who do not know the concept of routing, there is no obstacle to reading the following articles.

1. ASP. net mvc 3
2. install and configure ASP. net mvc 3 Environment
3. basic syntax of ASP. net mvc 3 Razor view Engine
4. ASP. net mvc 3 Razor view engine layout
5. ASP. net mvc 3 Controller
6. ASP. net mvc 3 Model [step by step through a simple example]

Okay. Let's talk about Routing.
First, if the namespace of Routing is System. Web. Routing, here, Routing is not unique to MVC 3 and is also used in webForm. Of course I have never used it, but I have used url rewriting for projects! If you have not used the url rewriting technology, it proves that your project does not require SEO.

Role of the second Routing:
1. Determine Controller 2. determine Action 3. determine other parameters (usually the parameters of the Action Method) 4. Pass the request to the Controller and Action according to the identified Controller Action.

Third, how does Routing work:
We think about a problem for the following url http://www.cnblogs/wlitsoft/blogs/123 why when I access this url is how to implement Controller is wlitsoft Action is blogs parameter is 123?
We all know that the MVC 3 Project has a global file (global. asax) Of course, this file is also used in webform. Let's take a look at its differences with webform, or what method it adds.

1 Routes. MapRoute (
2 "Default", // route name
3 "{controller}/{action}/{id}", // URL with Parameters
4 new {controller = "Home", action = "Index", id = UrlParameter. Optional} // default value of the Parameter
5 );

We will find the above lines of code. These lines of code define a routing matching rule. The following describes what the specific parameters mean.
-Name parameter: Rule name. It cannot be repeated. That is, the route name must be unique.

-Url parameters: Include the parameters to be identified, for example: {controller}/{action}/{id} Here {} is a placeholder. You can understand that you have used the Format method of the string class!
For example: string. Format ("{0} aaaa {1} bbb", "1", "2"); how do you understand!

-Defaults parameter: the default value of the url parameter. When we create an mvc project, when we run the browser, we can see that there is only one parameter in the address bar, such as http: // localhost: 32112/what does it go to the index page under home? This is the role of this parameter. It can define the default controller action and id parameter. Also, let's take a look at the code above. Why does the id not give a specific value but a UrlParameter. optional, because you cannot guarantee whether the id type is int or stirng, and write id = UrlParameter. optional specifies the default value of the type based on the id type. For example, if the int type is 0!

-Constraints parameter: this parameter does not appear in the above Code. I will explain it in advance and then read the code later!
This parameter is used to limit the rule of each parameter or the constraints attribute of the http request type. It is a RouteValueDictionary object, that is, a dictionary table. However, the value of this dictionary table can be either of the following: 1. A string used to define a regular expression. Regular Expressions are case-insensitive. 2. an object that implements the IRouteConstraint interface and contains the match method.
For example, you can use a regular expression to specify the parameter format. For example, the controller parameter can only contain four digits.

New {controller = @ "\ d {4 }"}

Currently, the IRouteConstraint interface can limit the request type.
For example, to restrict a routing rule, you can only process GET requests:

HttpMethod = new HttpMethodConstraint ("GET", "POST ")

Fourth, how to optimize the url
For a website that is SEO friendly, the number of URLs must not exceed three layers: but according to our default matching rule {controller}/{action}/{id}, It is Layer 3 and does not comply with SEO. What should I do? You can modify {controller}/{action}-{id} slightly. We all know that C #'s naming rule is that letters, numbers, underscores (_) cannot start with a letter, therefore, the url mapped from {action}-{id} is not matched into a variable.

Fifth, route matching has a priority.
Route matching has a priority, that is, when you define a routing rule, there is a sequence. If you define a very complex route, but you put it at the bottom, it happens that the preceding routing rules are correct, and you will never match the route you have defined. What should I do if I place a route that is not easily matched on the top and the route that is most easily matched on the bottom? Here I have to say that there is a route that can match all URLs. See the following code.
{* AllUrl}

Area 6. For example, a management system has background functions! However, what should we do if we want to separate the backend management module from the website front-end or, in this case, the backend management is saved as a separate web. config configuration file? Here, the concept of region comes out. We first create a region.

After the event, you will see a AreaAdminAreaRegistration. cs file to open it.
Copy code

1 public override void RegisterArea (AreaRegistrationContext context)
2 {
3 context. MapRoute (
4 "AreaAdmin_default ",
5 "AreaAdmin/{controller}/{action}/{id }",
6 new {action = "Index", id = UrlParameter. Optional}
7 );
8}

Copy code

How can I identify a global file by rewriting a method? View global files

1 protected void Application_Start ()
2 {
3 AreaRegistration. RegisterAllAreas ();
4
5 RegisterRoutes (RouteTable. Routes );
6}

The 3rd line is defined, so the region routing rule has no difference except that the preceding AreaAdmin region name is added! Next we will create a new Controller, such as AdminHome. We should first avoid renaming it with the previous Controller for a while and then explain why. View the running result

It's normal! But if I want to create a new HomeController, it is to create a Controller that was previously used at the front-end. Run it.

No problem, right! Next, let's access another homecontroller, which is the one at the front-end. Let's see what went wrong.

 

Something went wrong, right! Because there are two homecontrollers in the program, it does not know which one to access !, Therefore, according to the error message, we have to add something to the original route and add a namespace. Differentiate two homecontrollers
New string [] {"_ 2012_6_16Mvc2Test.Controllers "}

OK.

7. Route Test
We cannot guarantee that the routing rules we write will be matched. The following describes a tool designed to analyze route matching. What is RouteDebug?
First introduce the dll and then add the following code to the Application_Start () method in the global file:

RegisterRoutes (RouteTable. Routes );
RouteDebug. RouteDebugger. RewriteRoutesForTesting (RouteTable. Routes );

Let's get everything done and run it!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.