Asp.net MVC uses partialview to construct a custom menu

Source: Internet
Author: User

In vs2010, the menus generated by using the templates provided by Asp.net MVC are fixed and cannot be changed. The following uses partialview to implement a simple level-1 menu.

1) Change _ layout. cshtml to @ {html. renderaction ("menu", "home") in <nav> ");}

 
<Div class = "float-Right"> <section id = "login"> @ HTML. partial ("_ logonpartial") </section> <nav >@{ HTML. renderaction ("menu", "home") ;}</nav> </div>

MVC will call the menu method of homecontroller to display the menu

2) Add the menu method in homecontroller and return partialview.

 Public Partialviewresult menu ()
{
List <menuitem> menus = New List <menuitem> ();
Menus. Add ( New Menuitem {text = " Home " , Controller = " Home " , Action = " Index " });
Menus. Add ( New Menuitem {text = " Job " , Controller = " Job " , Action = " Index " });
Menus. Add ( New Menuitem {text = " About " , Controller = " Home " , Action = " About " });
Menus. Add ( New Menuitem {text = " Contact " , Controller = " Home " , Action = " Contact " });
Return Partialview ( New Menumodel {menus = menus });
}

3) define a new partialview named menu. cshtml.CodeTo:

 
@ Model mvcdemo. models. menumodel <ul id = "menu"> @ foreach (VAR item in model. menus) {<li> @ HTML. routelink (item. text, new {controller = item. controller, Action = item. action}) </Li >}</ul>

You can use partialview to customize multi-level menus and easily control permissions.

The complete code is as follows:

Http://files.cnblogs.com/huyq2002/MVCDemo.zip

To run this example, you may need to install Asp.net mvc4.

 

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.