We have a site where the Layout is set based on a dbconfig in
~/Views/_ViewStart.cshtml like so
@{
Layout = ViewContext.ViewBag.MyConfig.ThemeName;
}
And all's working fine except when we added a Emails folder to views ( for the Postal Nuget Package ) with it's own ViewStart at
~/Views/Emails/_ViewStart.cshtml
which contains
@{ Layout = null; /* Overrides the Layout set for regular page views. */ }
It's used for sending HTML formatted emails in code like so
dynamic email = new Email("<nameofView>"); // this is in folder ~/Views/Emails/
email.To = to;
.... other fields....
email.Send();
However, I'm getting an exception on this line
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: }
Any pointers on why it's picking up the ViewStart from ~/Views and not from ~/Views/Emails ?
You have to remember that although ~/Views/Emails/_ViewStart.html
will be used, the 'root' _ViewStart
is being executed beforehand as well.
Just change your root _ViewStart
to prevent the Exception
from being thrown:
@{
Layout = ViewContext.ViewBag.MyConfig != null ? ViewContext.ViewBag.MyConfig.ThemeName : null;
}
Your ~/Views/Emails/_ViewStart.html
will follow and set your Layout
properly.