0

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 ?

Kumar
  • 10,997
  • 13
  • 84
  • 134
  • what email constructor takes . if it is relative path to view then you wrote it with < > – qwr Jun 04 '13 at 17:33
  • @QWR the email constructor uses "ViewName", the relative path was for explaining the path for those not familar with Postal package, will change it – Kumar Jun 04 '13 at 19:35
  • rename your own _ViewStart to see if it will work . and contact to Postal package creater about this issue . – qwr Jun 04 '13 at 19:58

1 Answers1

1

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.

haim770
  • 48,394
  • 7
  • 105
  • 133
  • 1
    oops! was under the impression either/or and not both, something new for today, thanks – Kumar Jun 04 '13 at 20:10