0

我们有一个站点,其中基于 dbconfig 设置布局

~/Views/_ViewStart.cshtml like so
@{
    Layout = ViewContext.ViewBag.MyConfig.ThemeName;
}

一切正常,除非我们将一个电子邮件文件夹添加到视图中(用于邮政Nuget 包),并使用它自己的 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 的任何指示?

4

1 回答 1

1

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

只需更改您的根目录_ViewStart以防止Exception被抛出:

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

~/Views/Emails/_ViewStart.html将遵循并Layout正确设置您的。

于 2013-06-04T20:03:35.433 回答