ASP. net mvc Case Study (III)

Source: Internet
Author: User

Preface

In the previous article, we implemented the first ASP. net mvc page. For those who have never touched this framework, they may be confused in some places. So in this article, I will introduce some ASP from a global perspective through the graphic and text methods. net mvc operating mechanism, which can help friends better understand the subsequent articles.

Global

First, let's take a look at a picture. As this picture is made by myself, it is not from the official Microsoft website. If there is anything that is not in place, look at haihan!


First, the user sends a url request to the server through a Web browser. The requested url is no longer in xxx. aspx format, but http: // HostName/ControllerName/ActionName/Parameters. This request is intercepted by the routing ing System of ASP. net mvc. Route ing can be performed in Global. configure in asax. Let's talk about it later. According to the ing rules, the routing ing System parses the Controller name ControllerName, Action name ActionName, and Parameters. Then, it looks for the ControllerNameController under the Controllers directory. the cs Controller class, by default, the system always looks for the "Controller name + Controller" class under the Controllers directory, and then finds the method with the same name as ActionName under this class, after finding it, PASS Parameters as a parameter to this method, and then the Action method starts to be executed. After completion, the corresponding view is returned. By default, the aspx file with the same name as ActionName under the directory with the same name as ControllerName under the Views directory will be returned, and ViewData will be passed to the view. ViewData generally contains the control values displayed in the control view and the data required for displaying the view.

Let's review the request process on the homepage in the previous article. The url we passed is http: // localhost/Home/Index. Under the default routing rule, set ControllerName to "Home" and ActionName to "Index" without parameters. Therefore, the system finds the Index method of the HomeController class under the Controllers directory, and finds the method successfully. This method calls the Mock Model to retrieve some data and put it in the corresponding ViewData key value. Then return to the view. The returned value is Index. aspx under Home under Views. The data in ViewData is displayed in a certain format, so a typical ASP. net mvc call is completed.

Routing

It can be seen from the above that routing is very important in ASP. net mvc. It directly determines how the url is parsed, so it determines how the system works. Then, let's unveil the mystery of routing.

Open the Global. asax. cs file in our Demo and you can see the following code:

Global. asax. cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace MVCDemo
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
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 = "" }  // Parameter defaults
);

}
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
}
}
}

Let's focus on it. Note that there is a routes. MapRoute Method on it. This method adds a routing rule to the system. The only rule is added by default. The first parameter is the rule name, which is a common string. The key is the second parameter. It is also a string, but it describes how to parse the url. It can be understood in this way that it describes how to match the part after the url string HostName, where {} indicates Parameter Matching. If not, it indicates string matching.

For example, the preceding {controller}/{action}/{id} indicates that if there are three strings separated by "/" after the HostName, the url will be matched, it is resolved to the Controller name, Action name, and a parameter named "id. If you enter http: // localhost/Home/Index/1, "1" is treated as the parameter id, but if you request http: // localhost/Home/Index/1: // localhost/Home/Index/1/2. Sorry, your request cannot be successful because this routing rule cannot match your url because your HostName is followed by four sections, however, this routing rule can only match three segments.

You may have noticed that http: // localhost/Home/Index has only two segments after HostName. How can this problem be matched? This is the third parameter of the MapRoute method. This parameter is used to set the default values for each {} matching segment in the preceding rule. As shown above, the default value of id is "", that is, null. Therefore, although the specified id is not displayed in http: // localhost/Home/Index, it can still be matched successfully. The default value is null. If you remove id = "", you will find that http: // localhost/Home/Index cannot match. Similarly, http: // localhost/Home/can also be matched successfully, because {action} defaults to Index and http: // localhost/can also be matched successfully, because {controller} is Home by default, http: // localhost/Home/Index and http: // localhost/are equivalent under this default value.

Based on the above analysis, we come to an important conclusion: When the default value is set, the ing rule is "less than more", and a small part is replaced by the default value.

In the above matching rules, all three matching segments are in braces and all are Parameter Matching. Next we will talk about strong string matching. For example, we need a url such as http: // localhost/Category/Detail/Name. According to the above matching rules, the value of the Name segment will be matched to the id, but what should we do if we want to use the parameter "name" in the Detail method of CategoryController instead of the parameter "id? It is easy to add a matching rule:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace MVCDemo
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Category",                                              // Route name
"Category/Detail/{name}",                           // URL with parameters
new { controller = "Category", action = "Detail", name = "" }  // Parameter defaults
);
routes.MapRoute(
"Default",                                              // Route name
"{controller}/{action}/{id}",                           // URL with parameters
new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
);
}
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
}
}
}

We can see that a rule is added before the default rule, where the Controller name and Action name are no longer parameters, but become a strong string {}). In this case, when the request url is in the form of http: // localhost/Cateogry/Detail/para, the newly added rule will be directly matched, the value of para is not assigned to an id, but to a variable named name.

Note that our new routing rules must be put in front of, because ASP. net mvc will match the first matching routing rule from top to bottom.

View

After the routing rules are completed, let's talk about the view.

As mentioned above, the return type of the Action method is ActionResult. In fact, this return type is not limited to the ViewResult returned by the View method. There are many implementations. Here are several examples.

ViewResult: Generally, An aspx file is rendered and returned by the View method.

RedirectToResult: redirects the browser, which is returned by the Redirect method.

RedirectToRouteResult: directly submit it to the next Action, which is returned by the RedirectToAction method.

There are a few other articles that I will not talk about first, because there are basically no other articles available in the future. Friends can read the relevant materials by themselves.

Summary

After reading this article, we have removed 90% of the obstacles. In the following article, we will continue with our instance. In the next article, we will complete the announcement publishing function to see how ASP. net mvc processes the transmission of form information.

This article is from Zhang Yang's blog T2's Notebook

  1. ASP. net mvc Case study 1)
  2. ASP. net mvc Case study 2)
  3. ASP. net mvc case study 4)
  4. ASP. net mvc case study 5)
  5. ASP. net mvc case 6)
  6. ASP. net mvc case study 7)

Related Article

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.