To put it bluntly, I have already worked on several company projects, but I have not systematically studied ASP. NET MVC. Simply relying on previous experience, and then encountering problems google, the project was actually completed. Now it's a little blank. Let's take a look at MVC. Below we will record some of my study notes for future reference. 1. When you run an ASP. net mvc project, a route table is created at the beginning of the program. The related code is in global. asax. At the beginning, the program registers your routing rules to RouteTable. Routes with the sex Application_Start.
Using System; using System. collections. generic; using System. linq; using System. web; using System. web. mvc; dusing System. web. routing; namespace MVCApplication1 {// 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 = UrlParameter. optional} // Parameter defaults);} protected void Application_Start () {AreaRegistration. registerAllAreas (); RegisterRoutes (RouteTable. routes );}}}
When you enter the URL: Home/Index/3, the URL exactly matches the default route. Simply put, the Controller = Home, Action = Index, id = 3 program will call HomeController. index (3)
How to add a custom routeFor example, you need to display an archived blog list. If you want the URL to be like this Archive/04-07-2011, then your route should be defined as follows.
routes.MapRoute(
"Blog", // Route name
"Archive/{entryDate}", // URL with parameters
new { controller = "Archive", action = "Entry" } // Parameter defaults
);
When you enter Archive/04-07-2011, the program runs ArchiveController. Entry (DateTime enteryDate ). At this time, if you input Archive/MVC, you will get an error, because "MVC" is only a string type, not a DateTime type. How can we avoid this situation. You need to create a constraint for this route.
How to Create a constraint for a route
routes.MapRoute(
"Blog", // Route name
"Archive/{entryDate}", // URL with parameters
new { controller = "Archive", action = "Entry" }, // Parameter defaults
new { entryDate = @"d{2}-d{2}-d{4}" }
);
Of course, my constraints on this date are simple, just for example. In this way, URLs that do not meet our requirements, such as Archive/MVC, will not match this route, and it will find other routes to match. Of course, if they do not match, an error is returned. Now, we will record it here today. Later I saw a new article and wrote it again :) green channel: please pay attention to my favorite article and contact me