asp.mvc (4)---Master Pages
mvc前三章都是必须知道的(所以不用做备忘),
被忽视的往往是小东西,但这些东西会左右思路,决定成败。
1 如何创建和使用一个Master
在Master页面时设置
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server"></asp:ContentPlaceHolder>
然后再使用页面上 :
runat="server">
<h2>Custom Master Demo</h2>
</asp:Content>
2、Control中ActionResult来确定一个页面的Master
if (DateTime.Now.Second % 2 == 0)
else
masterName = "Site";
return View("Index", masterName);
3、通过重写试图来决定
{
protected override void OnPreInit(EventArgs e)
{
if(DateTime.Now.Second%2==0)
Page.MasterPageFile = "~/Views/Shared/Site2.Master";
else
Page.MasterPageFile = "~/Views/Shared/Site.Master";
base.OnPreInit(e);
}
}
然后在页面上实现标签:
4、使用一个基础控制类来实现
public class BaseController : Controller
protected override void OnActionExecuted(
ActionExecutedContext filterContext)
{
var action = filterContext.Result as ViewResult;
if (action != null)
{
if (DateTime.Now.Second % 2 == 0)
action.MasterName = "Site2";
else
action.MasterName = "Site";
}
base.OnActionExecuted(filterContext);
}
}
然后再使用的时候
public class HomeController : BaseController 实现所有。
5、传递数据到Master页面
首先设计一个 Controller
public class BaseController : Controller
public BaseController()
{
List<string> manufacturers = new List<string>();
manufacturers.Add("Ford");
manufacturers.Add("Toyota");
manufacturers.Add("Chevy");
manufacturers.Add("Dodge");
manufacturers.Add("Nissan");
manufacturers.Add("Mazda");
manufacturers.Add("Audi");
ViewData["manufacturers"] = manufacturers;
}
}
然后让相应的controller来继承他
public class HomeController : BaseController
这样就可以在Master通过 ViewData["manufacturers"]来访问数据了
6、如何在Master中使用编辑好的视图
首先,建设一个Control,注意ChildActionOnly
public ActionResult _Categories()
{
List<string> navigation = new List<string>();
navigation.Add("Books");
navigation.Add("Cars");
navigation.Add("Clothes");
navigation.Add("Computers");
ViewData["navigation"] = navigation;
return View();
}
然后建立 _Categories.ascx
在Master中这样使用
<%= Html.Action("_Categories", "Home") %>
7、嵌套的Master
......................................................会了1,难道2还远么?一样的!呵呵