MVC route Customization and view search rules

Source: Internet
Author: User

This article about MVC Routing and view Rules was originally sent yesterday, but I am really a little lazy, finally today Unbearable. MVC is a little bit more than it is now (and now it's a dish), thinking it will work, but sometimes it's curious why it can find a controller? Why does the controller return to view () and find the views, and why the view must be built under the views file? as if to say a bit more, the next side of the example, side analysis!

MVC Route Customization

I believe that the MVC route configuration we all know some, in fact, this is not the focus of this chapter.

When creating an MVC project, The root directory is >>app_start>>routeconfig, the class is used to configure the route, and there will be a default route at the Beginning.

Brief introduction: first Parameter: route name (unique), second parameter url: It is important to note that {controller}, {action} are equal placeholders. The third parameter is the default Route.

Scenario: when your controller needs to be categorized according to different functions, if you need to make a different product, you want to put the controller of the same product Together. You can do this:

Add a routing Rule:

1          public Static voidregisterroutes (routecollection routes)2         {3Routes. Ignoreroute ("{resource}.axd/{*pathinfo}");4 Routes. MapRoute (5Name"Product",6Url:"product/aboutprice/{controller}/{action}/{id}",7DefaultsNew{controller ="Sale", action ="Index", id =urlparameter.optional}8             );9 Ten Routes. MapRoute ( oneName"Default", aUrl:"{controller}/{action}/{id}", -DefaultsNew{controller ="Home", action ="Index", id =urlparameter.optional} -             ); the}

Note: Routing rule matching is top-down, and priority-matching routes must be written at the Top. Because the route match succeeds, it will not continue to Match. of course, The controller directory we created must also Match.

Results:

  

MVC View Finding rules  in the above section even if we have customized the route, but the location of the view is still placed in the views folder, (otherwise, The result is definitely not found) we also hope that the view location is Available.

The view that you want the controller to return can be in this directory:

① first, We need to write a class to customize the mapping rules for our view, which I built in the App_start folder, along with other configuration Classes.

1   public Sealed classMyviewrule:razorviewengine2     {3          publicmyviewrule () {4 5Viewlocationformats =New string[] {6                 //The view we defined looks for rules, like the routing configuration, which is read from top to bottom, and if there are views on all two paths, it will show the first One. 7                 "~/productviews/aboutprice/{1}/{0}.cshtml",8                 //This is the default setting, I think it can be deleted, {1} represents the controller name, {0} represents the view name9                 "~/views/{1}/{0}.cshtml",Ten                 "~/views/shared/{0}.cshtml" one             }; a         }
-}

② then, You need the global Global.asax.cs inside the registration of our rules, The code is as Follows:

1    public classMvcApplication:System.Web.HttpApplication2     {3         protected voidApplication_Start ()4         {5 Arearegistration.registerallareas ();6 filterconfig.registerglobalfilters (globalfilters.filters);7 routeconfig.registerroutes (routetable.routes);8 bundleconfig.registerbundles (bundletable.bundles);9             //above is the project to create the default registration, the following two: first the original rules empty, and then set us to add ()Ten ViewEngines.Engines.Clear (); oneVIEWENGINES.ENGINES.ADD (NewMyviewrule ()); a         } -}

 

Test Results:

Error:The view at ' ~/productviews/aboutprice/sale/index.cshtml ' must derive from webviewpage, or Webviewpage<tmodel .

Probably means: there is no inheritance of this webviewpage class, at compile time, This view page will also generate a class, there are two ways to Solve:

① Let it inherit that class directly (@inherits System.Web.Mvc.WebViewPage)

1 @{2Layout =NULL;3 }4 5<! DOCTYPE html>6 @inherits System.Web.Mvc.WebViewPage789<meta name="Viewport"Content="Width=device-width"/>Ten<title>Index</title> one a<body> -<div> my view location is not the same oh! -</div> the</body> -

of course, The above approach, there is a bad thing is to add a view every time you have to write once, the view is very inconvenient. We can also let it inherit from the config file webviewpage

② Add a configuration file (web. Config) that inherits Webviewpage under the pages Node. or, under the default create views folder, There is a web. config copy under/productviews/aboutprice . (local configuration file, Nearest Principle)

<pagebasetype= "System.Web.Mvc.WebViewPage"></  Pages>

Results:

Summarize

About MVC How to find the controller, the controller how to match the view I want to be able to give the need of a small partner a little help, is also a summary of their own, the wrong place, welcome Correction.

Programmers on the road of learning never afraid of encountering problems, this is a growth, but also a kind of exercise, in this extremely need experience of the industry, the fall is those who muddle through. Encounters the problem, diligently solves, always has the steady, at that time is satisfies the joyful, the mutual encouragement!

MVC route Customization and view search rules

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.