我们有一个基于
中的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的任何指针?
答案 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
。