RuntimeBinderException,Razor没有在子文件夹中拾取_ViewStart

时间:2013-06-04 17:18:14

标签: c# .net asp.net-mvc asp.net-mvc-4 postal

我们有一个基于

中的dbconfig设置布局的站点
~/Views/_ViewStart.cshtml like so
@{
    Layout = ViewContext.ViewBag.MyConfig.ThemeName;
}

所有工作正常,除非我们在视图中添加了一个Emails文件夹(对于Postal Nuget Package),并且在

上有自己的ViewStart
~/Views/Emails/_ViewStart.cshtml 

包含

@{ Layout = null; /* Overrides the Layout set for regular page views. */ }

它用于以类似代码发送HTML格式的电子邮件

        dynamic email = new Email("<nameofView>"); // this is in folder ~/Views/Emails/
        email.To = to;
        .... other fields....
        email.Send();

但是,我在这一行得到例外

    Layout = ViewContext.ViewBag.MyConfig.ThemeName;


 Cannot perform runtime binding on a null reference
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Cannot perform runtime binding on a null reference

Source Error:


Line 1:  @{
Line 2:      Layout = ViewContext.ViewBag.MyConfig.ThemeName;
Line 3:  }

关于为什么它从〜/ Views而不是从〜/ Views / Emails中获取ViewStart的任何指针?

1 个答案:

答案 0 :(得分:1)

您必须记住,虽然~/Views/Emails/_ViewStart.html 会被使用,但“root”_ViewStart也会被预先执行。

只需更改根_ViewStart即可防止Exception被抛出:

@{
    Layout = ViewContext.ViewBag.MyConfig != null ? ViewContext.ViewBag.MyConfig.ThemeName : null;
}

您的~/Views/Emails/_ViewStart.html将会关注并正确设置Layout