2011-04-11 93 views
2

我有两个操作称为“a”和“b”。我也有两种看法。这些观点的布局是不同的。 用于:ASP.Net中的错误视图的动态布局MVC

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

对于b:

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

也错误视图是共享的。

如何为错误视图使用动态布局。例如,当处理动作“a”时出现错误,错误在动作布局“a”中显示,如果在处理动作“b”时出现错误,错误在动作布局“b”中显示?

+0

http://stackoverflow.com/questions/5059323/asp-mvc-3-use-different-layouts-in-different-views – Adam 2013-04-05 14:45:39

回答

0

你可以尝试从控制器动作过关的布局:在会话中设置当前布局,然后在错误控制器读取出来,然后把它传递给视图通过ViewBag属性:

public ActionResult A() 
{ 
    // Do things 

    // Set the layout 
    Session["currentLayout"] = "~/Views/Shared/_X.cshtml"; 

    return View(); 
} 

ErrorController :

@{ 
    Layout = ViewBag.ErrorLayout; 
} 

public ActionResult NotFound() // 404 
{ 
    // Set the layout 
    ViewBag.ErrorLayout = Session["currentLayout"]; 

    return View(); 
} 
在你的错误观点

然后10

我会授予你这个不会赢得美容奖;可能还有其他方法。

例如,看看这个答案如何在一个ActionFilter设置布局:How to set a Razor layout in MVC via an attribute filter?

你可以写你自己的错误过滤器从HandleError继承,并在那里设置布局。

6

你可以写一个辅助方法:

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(); 
} 
+0

很好的解决方案。 +1。 – 2012-05-30 09:34:26

1

希望这种帮助ü....在Asp.Net MVC呈现布局的各种方式。

方法1:

@{ 
var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToString(); 

string layout = ""; 
if (controller == "Admin") 
{ 
layout = "~/Views/Shared/_AdminLayout.cshtml"; 
} 
else 
{ 
layout = "~/Views/Shared/_Layout.cshtml"; 
} 
Layout = layout; 
} 
:控制布局呈现由浏览文件夹的根目录下使用_ViewStart文件

我们可以在_ViewStart文件通过使用下面的代码更改布局的默认渲染

方法2:从ActionResult返回布局

我们还可以通过使用以下代码从ActionResult返回布局来覆盖默认布局渲染:

public ActionResult Index() 
{ 
RegisterModel model = new RegisterModel(); 
//TO DO: 
return View("Index", "_AdminLayout", model); 
} 

方法3:

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

:与顶部

每个视图我们也可以通过使用下面的代码定义视图上的布局覆盖默认布局呈现定义布局谢谢