如何在 ASP.NET Core MVC 中指定不同的布局 [英] How do I specify different Layouts in the ASP.NET Core MVC
问题描述
我想在我的应用程序中有 2 个单独的布局.假设一个是网站的公共部分,另一个是空的,出于某些我们需要的原因.
I would like to have 2 separate Layouts in my application. Let say one is for the Public section of the website and the other is empty for some reasons we need.
在 Core 之前,我可以这样做来定义一个过滤器:
Before Core I could do this to define a filter:
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;
}
}
}
现在 ViewResult 没有 MasterName 属性.是否可以现在做,而不是在 View 中使用布局定义.
Now the ViewResult do not have the MasterName property. Is it possible to do now, and not to use in the View the layout definition.
推荐答案
你仍然可以做一些与你原来的方法非常相似的事情,使用 ViewData
来传递布局名称(虽然我会创建它作为 结果过滤器):
You can still do something very similar to your original approach, using ViewData
to pass around the layout name (Although I would create it as a Result Filter):
public class ViewLayoutAttribute : ResultFilterAttribute
{
private string layout;
public ViewLayoutAttribute(string layout)
{
this.layout = layout;
}
public override void OnResultExecuting(ResultExecutingContext context)
{
var viewResult = context.Result as ViewResult;
if (viewResult != null)
{
viewResult.ViewData["Layout"] = this.layout;
}
}
}
然后在_ViewStart.cshtml
文件中:
@{
Layout = (string)ViewData["Layout"] ?? "_Layout";
}
最后,假设您创建了一个像 Views/Shared/_CleanLayout.cshtml
这样的新布局,您可以在任何控制器或操作上使用该属性:
Finally, assuming you create a new layout like Views/Shared/_CleanLayout.cshtml
, you can use that attribute on any controller or action:
[ViewLayout("_CleanLayout")]
public IActionResult About()
{
//...
}
这篇关于如何在 ASP.NET Core MVC 中指定不同的布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!