2

I have an asp.net Web Forms application that needs to send emails. I like the Razor syntax and as you can use Razor outside of MVC I thought I'd try and use that. I've seen that you can programmatically pass a template string to razor but I'd like to keep my razor templates as separate .cshtml files.

Does anyone have any simple, idiot-proof advice as to how to do this? I've tried to load them from file like this:

UserDetails userDetails = new UserDetails {Name = "Fred"};
string template = File.OpenText("Email/UserDetailsEmail.cshtml").ReadToEnd();            
string messageText = Razor.Parse(template, userDetails);

All to no avail. There's an exception finding the file. I'm using the razorengine dll.

I have everything else working, the smtp server etc, just not the views.

Any help appreciated.

Matt
  • 5,573
  • 4
  • 33
  • 37

2 Answers2

4

You need to get the full path to the file; relative paths will end up being relative to the wrong location.

Write

File.OpenText(Server.MapPath("~/Email/UserDetailsEmail.cshtml"))
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
1

I would use the MVCMailer tool which you can setup with Nuget and has scaffolding for creating the views.

It is a very well written app and can be added to yours easily:

https://github.com/smsohan/MvcMailer

http://www.codeproject.com/KB/aspnet/MvcMailerNuGet.aspx

Richard
  • 21,728
  • 13
  • 62
  • 101
  • Do you know how to call a razor view from within an web forms project. When I call 'PopulateBody(mailMessage, viewName: "UserDetails");' I get an exception: "Value cannot be null.\r\nParameter name: routeData". Are there any simple instructions for rigging MvcMailer up inside and web forms app? – Matt May 17 '11 at 15:24