我想知道是否可以基于路由动态地将布局添加到局部视图中。
例如:
这里的要点是我不想创建具有重复功能的另一个视图,而是动态设置Layout属性。
感谢。
答案 0 :(得分:1)
您可以创建自定义视图结果,以检查路径收集并执行PartialViewResult或ViewResult。并使用它而不是View()或PartialView()
// constructor goes here which accepts model and view name
public override void ExecuteResult( ControllerContext context )
{
ViewResultBase viewResult;
// some check
if( context.RouteData.Values || context.HttpContext.Request.RawUrl )
{
viewResult = new ViewResult();
}else
{
viewResult = new PartialViewResult();
}
viewResult.ExecuteResult( context );
}
答案 1 :(得分:0)
试试这个:
<强>动作强>
public ActionResult Index() {
ViewBag.Layout = null;
object layout;
if (RouteData.Values.TryGetValue("layout", out layout)) {
switch(layout.ToString())
{
case "Layout1":
ViewBag.Layout = "~/Views/Shared/_Layout.cshtml";
break;
// ...
}
}
return PartialView("Test");
}
<强>标记强>
@{
Layout = ViewBag.Layout;
}
<div>This is the test page...</div>
路由配置
routes.MapRoute(
"Default", // Route name
"{controller}/{action}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }); // Parameter defaults
routes.MapRoute(
"DefaultWithLayout", // Route name
"{layout}/{controller}/{action}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }); // Parameter defaults
}
或者只是
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{layout}", // URL with parameters
new { controller = "Home", action = "Index", layout = UrlParameter.Optional, id = UrlParameter.Optional }); // Parameter defaults