ASP.Net MVC中错误视图的动态布局 [英] Dynamic Layout for Error View in ASP.Net MVC

查看:80
本文介绍了ASP.Net MVC中错误视图的动态布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个动作,分别是"a"和"b".我也对他们有两种看法.这些视图的布局有所不同. 对于:

I have two action called "a" and "b". also I have two view for them. the layout of these views is difference. for a:

@{
    Layout = "~/Views/Shared/_X.cshtml";
}

对于b:

@{
    Layout = "~/Views/Shared/_Y.cshtml";
}

错误视图也是共享的.

如何为错误视图使用动态布局.例如,当在处理动作"a"时发生错误时,错误显示在动作"a"的布局中;如果在处理动作"b"时发生错误,则错误在动作"b"的布局中显示?

How can I use a dynamic layout for Error view. for example when an error occurred while processing action "a" the error show in layout of action "a" and if an error occurred while processing action "b" the error show in layout of action "b"?

推荐答案

您可以编写一个辅助方法:

You could write a helper method:

public static string GetLayout(this HtmlHelper htmlHelper)
{
    var action = htmlHelper.ViewContext.RouteData.GetRequiredString("action");
    if (string.Equals("a", action, StringComparison.OrdinalIgnoreCase))
    {
        return "~/Views/Shared/_X.cshtml";
    } 
    else if (string.Equals("b", action, StringComparison.OrdinalIgnoreCase))
    {
        return "~/Views/Shared/_Y.cshtml";
    }
    return "~/Views/Shared/_Layout.cshtml";
}

然后:

@{
    Layout = Html.GetLayout();
}

这篇关于ASP.Net MVC中错误视图的动态布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆