HTML. Action () and HTML. RenderAction () are similar to HTML. Partial () and HTML. RenderPartial () auxiliary methods. The Partial auxiliary method usually applies view tags in a separate file to help the view render a part of the view model. On the other hand, Action is to execute a separate controller operation and display the result. Action provides more flexibility and reusability, because controller operations can create different models and use separate controller context.
Purpose: To generate a menu
Menu Models,
[Csharp]
Public class Menu
{
Public List <MenuItem> Items {get; set ;}
}
Public class MenuItem
{
Public string Text {get; set ;}
Public string Url {get; set ;}
}
Write this Action in Controler,
[Csharp]
[ChildActionOnly]
Public ActionResult MyMenu ()
{
MvcLearn. Models. Menu m = new MvcLearn. Models. Menu ();
List <MvcLearn. Models. MenuItem> items = new List <MenuItem> ();
Items. Add (new MenuItem () {Text = "Baidu", Url = "http://www.baidu.com "});
Items. Add (new MenuItem () {Text = "Sina", Url = "http://www.Sina.com "});
Items. Add (new MenuItem () {Text = "IBM", Url = "http://www.ibm.com "});
Items. Add (new MenuItem () {Text = "Sohu", Url = "http://www.sohu.com "});
M. Items = items;
Return PartialView (m );
}
Create a PartialView-MyMenu. cshtml
[Csharp]
@ Model MvcLearn. Models. Menu
<Ul>
@ Foreach (var item in Model. Items)
{
<Li> <a href = "@ item. Url"> @ item. Text </a> </li>
}
</Ul>
Call this Action on the page to generate the View:
[Csharp]
@ Html. Action ("MyMenu ")
Action and PartialView must have the same name. Here they are all mymenus.
The following is the version of the parameter passed to the Action:
Modify the Action so that it can accept a MenuItem parameter. If it is not empty, add it to the menu.
[Csharp]
[ChildActionOnly]
Public ActionResult MyMenu (MenuItem mi)
{
MvcLearn. Models. Menu m = new MvcLearn. Models. Menu ();
List <MvcLearn. Models. MenuItem> items = new List <MenuItem> ();
Items. Add (new MenuItem () {Text = "Baidu", Url = "http://www.baidu.com "});
Items. Add (new MenuItem () {Text = "Sina", Url = "http://www.Sina.com "});
Items. Add (new MenuItem () {Text = "IBM", Url = "http://www.ibm.com "});
Items. Add (new MenuItem () {Text = "Sohu", Url = "http://www.sohu.com "});
M. Items = items;
// If the input parameter is not empty, add the Item to the menu.
If (mi! = Null)
M. Items. Add (mi );
Return PartialView (m );
}
You need to input parameters when calling the front-end interface:
[Csharp]
@ Html. action ("MyMenu", new {mi = new MvcLearn. models. menuItem () {Text = "haha", Url = <a href = "http://www.ms.com"> http://www.ms.com </a> }})
Author: diandian82