你可以在/Views/Public
文件夹中放置一个_ViewStart.cshtml
文件,它将覆盖/Views
文件夹中默认的文件,并指定所需的布局:
@{
Layout = "~/Views/Shared/_PublicLayout.cshtml";
}
类比一下,您可以在 /Views/Staff
文件夹中放置另一个 _ViewStart.cshtml
文件,并包含以下内容:
@{
Layout = "~/Views/Shared/_StaffLayout.cshtml";
}
你还可以指定在控制器操作中返回视图时应使用哪种布局,但这是针对每个操作的:
return View("Index", "~/Views/Shared/_StaffLayout.cshtml", someViewModel);
另一个可能性是使用自定义操作筛选器覆盖布局。正如您所看到的,有许多实现此目的的可能性。由您选择最适合您场景的方法。
更新:
根据评论部分的请求,这里提供一个选择主页面的操作筛选器示例:
public class LayoutInjecterAttribute : ActionFilterAttribute
{
private readonly string _masterName;
public LayoutInjecterAttribute(string masterName)
{
_masterName = masterName;
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext);
var result = filterContext.Result as ViewResult;
if (result != null)
{
result.MasterName = _masterName;
}
}
}
然后使用自定义属性装饰控制器或操作,指定你想要的布局:
[LayoutInjecter("_PublicLayout")]
public ActionResult Index()
{
return View();
}
Razor
视图删除布局,只需设置Layout = null;
。 - Leniel Maccaferri