I want to send email using old good approach of MVC 2 by converting code into MVC 3.
But it gives an error here:
Control control1 = vp1.LoadControl("/Views/Home/_SupportEmailAdmin.cshtml");
vp1.Controls.Add(control);
The error message:
Type ‘ASP._Page_Views_Home__SupportEmail_cshtml’ does not inherit from ‘System.Web.UI.UserControl’.
Is there a correct way to do it?
Here is the Code:
ViewBag.SupportRequest = this.SupportRequest;
ViewPage vp1 = new ViewPage();
vp1.ViewData = ViewData;
Control control1 = vp1.LoadControl("/Views/Home/_SupportEmailAdmin.cshtml");
vp1.Controls.Add(control);
StringBuilder sb1 = new StringBuilder();
using (StringWriter sw1 = new StringWriter(sb1))
{
using (HtmlTextWriter tw1 = new HtmlTextWriter(sw1))
{
vp1.RenderControl(tw1);
}
}
sb1.Insert(0, @"<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Strict//EN"" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd""><html xmlns=""http://www.w3.org/1999/xhtml""><body>");
sb1.Append("</body></html>");
MailMessage msg1 = new MailMessage(new MailAddress(this.SupportRequest.EMail, this.SupportRequest.Name),
new MailAddress(from, fromName));
msg1.Subject = fromSubject;
msg1.IsBodyHtml = true;
msg1.Body = sb1.ToString();
....
In two words the question is how to use the MVC 3 page template to render it as text and send it.
UPDATES:
The finial solution…
#region Send Support Request to Admin
StreamReader streamReader1 = new StreamReader(Server.MapPath("/Views/Home/_SupportEmailAdmin.cshtml"));
string emailTemplate1 = streamReader1.ReadToEnd();
streamReader1.Close();
string result1 = Razor.Parse(emailTemplate1, new { Name = sr.Name, EMail = sr.EMail, Subject = sr.Subject, Message = sr.Message });
StringBuilder sb1 = new StringBuilder();
sb1.Insert(0, @"<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Strict//EN"" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd""><html xmlns=""http://www.w3.org/1999/xhtml""><body>");
sb1.Append(result);
sb1.Append("</body></html>");
MailMessage msg1 = new MailMessage(new MailAddress(sr.EMail, sr.Name),
new MailAddress(from, fromName));
msg1.Subject = fromSubject;
msg1.IsBodyHtml = true;
msg1.Body = sb1.ToString();
#endregion
smtp.Send(msg1);
and the content of cshtml
file
<table>
<tbody>
<tr>
<td>
Name
</td>
<td>@Model.Name
</td>
</tr>
<tr>
<td>
Email
</td>
<td>@Model.EMail
</td>
</tr>
<tr>
<td>
Subject
</td>
<td>@Model.Subject
</td>
</tr>
<tr>
<td>
Message
</td>
<td>@Model.Message
</td>
</tr>
</tbody>
</table>
Take a look at the RazorEngine project
http://razorengine.codeplex.com/
and maybe ready to use solution – MvcMailer
https://github.com/smsohan/MvcMailer/wiki/MvcMailer-Step-by-Step-Guide