如何在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屋!