Routing attributes for ASP. NET MVC and master page rendering (12)

Source: Internet
Author: User

Objective

In this section we begin to talk about the basics, as the topic says, that when you learn or use MVC, you have to know what's new in the latest iteration, at least the difference between MVC 3, MVC 4, or MVC 5, and not when you're using a lower version. There are certain features that are so confusing that it's a matter of code that we need to know.

Topic

Prior to MVC 5, it was a contract-based route, as follows:

  routes.            Mapmvcattributeroutes (); Routes. MapRoute (name:   default   "   {controller}/{action}/{id}   , Def Aults:  new  {controller =  " home  , action = "  index  , id = urlparameter.optional} );

The corresponding controller is home, and the method is index. At this point in the controller and the method is actually present, when we have some kind of demand does not want to correspond to its real route, then does not satisfy our request. So in MVC 5 and Web APi 2 There is a new feature called the routing feature. With our defined controllers and actions, we can take advantage of the routing features to control URLs more flexibly. Please look down.

MVC routing Characteristics Controller routing characteristics

At this point we add this controller routing attribute, and if we do not need to perform a special mapping for an action at this time, then all actions under that controller will be applied.

    [Routeprefix ("myhome")]      Public class Homecontroller:controller    {               public  actionresult Index ()        {            return  View ();        }     } 

This corresponds to the following:

We can also define the default action, as follows:

    [Routeprefix ("myhome")]    [Route ("{action = index}")]      Public class Homecontroller:controller    {       public  actionresult Index ()        {            return  View ();        }    } 

Great, it went wrong, and the results are as follows:

Unexpectedly, the default action is eventually modified as follows, and the space between the deletions is good:

[Route ("{action=index}")]
Action Route attribute

By defining an attribute on the action to apply it to the specific action method on the controller.

     Public classHomecontroller:controller {[Route ("cnblogs/{id:int:min (1)}")] //access: CNBLOGS/1  PublicActionResult Index (intID) {returnView (); } [Route ("Cnblogs/about")] //access: Cnblogs/about  PublicActionResult About () {Viewbag.message="Your Application description page."; returnView (); }         Publicactionresult Contact () //access: Home/contact {viewbag.message="Your Contact page."; returnView (); }    }
Zone Routing characteristics

We can also use the Routing zone feature to define a controller to belong to a region, we know to find the method under the region through the zone registration class to achieve, if we have all the controllers in a region using the regional characteristics, then the region registration class is arearegistration can be removed. Let's take a look at the following example.

[Routearea ("Admin")] [Routeprefix ("Menu")] [Route ("{action}")]     Public classMenucontroller:controller {//Routing:/admin/menu/login         PublicActionResult Login () {returnView (); }        //Routing:/admin/menu/products[Route (" Products")]         PublicActionResult getproducts () {returnView (); }        //Routing:/categories[Route ("~/categories")]         PublicActionResult Categories () {returnView (); }    }
Attention

(1) The routing attribute must be configured before a contract-based route.

(2) When a combination of routing attributes and contract-based routing is not used at this time, the routing attribute is valid based on the contract route.

(3) When there is only a routing attribute, the action method that defines a contract-based approach without using the routing attribute is not accessed at this time.

Time to use routing features

Contract-based routing is more complex and can support a deterministic URI, but we can define the URI pattern very easily by using the routing attribute.

For example, the following scenario: When the online shopping customer orders, according to the customer ID to place orders, there is a similar URI: client/clientid/orders , at this time it is difficult for us to use the contract-based routing to control, Even the ability to use contract-based routing can be done, but it can be slightly complex or not very quantifiable to show what we describe. So, based on the description, we can easily write with the routing characteristics as follows:

        [Route ("client/{clientid}/orders")]          Public ienumerable<string> getordersbyclient (int  clientId)        {            return enumerable.empty<string>();        }
To start the routing feature

It says so much, even if using the routing feature as described above would have no effect, since the routing feature is not started by default in MVC 5, we need registerroutes in the routing profile Routeconfig method to register the following, so easy.

     Routes. Mapmvcattributeroutes ();

If you use only routing attributes, you can remove the following contract-based routing in this method.

            routes. MapRoute (                "Default",                "{Controller}/{action}/{id}  ",                new"Home""Index  ", id = urlparameter.optional}            );
MVC renders Master Pages

The templates in MVC must be familiar, but in the default project to build MVC, there is a master default motherboard page _viewstart under the views/shared/ folder. What we need to discuss here is the different ways to render the master page.

So the problem is, there might be a scenario: when you need to control user access permissions, at this time the user of different roles corresponding master Page page may be different, at this time we should do?

Way One

We can make the following changes in the _viewstart master page to correspond to different master pages, different roles corresponding to different controllers, when authorized to the corresponding controller to render the corresponding master page, so at this point we just need to get the controller.

@{    varController = httpcontext.current.request.requestcontext.routedata.values["Controller"].    ToString (); stringLayout =""; if(Controller = ="Admin") {Layout="~/views/shared/_adminlayout.cshtml"; }    Else{Layout="~/views/shared/_layout.cshtml"; } Layout=layout;}
Way Two

Because the view method has eight overloads, the last overloaded three parameters are the view name, the master page name, and the model object. So at this point we can render the master page directly through ActionResult.

Public New Usermodel ();   return View ("Index""_adminlayout", model);}
Mode three

The most straightforward is to define the master page in the corresponding page.

" ~/views/shared/_adminlayout.cshtml " ;}
Summarize

This section describes the routing features in MVC 5 and the ways in which the master page is rendered, and where inappropriate or not, it is welcome to add and criticize. We'll see you next day.

Routing attributes for ASP. NET MVC and master page rendering (12)

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.