1

I have two different views as below.

First: /Invoice/Print/?InvID=12345
Second: /Account/Index

Second view has a button to send Email. It will send the Invoice in email. Invoice email format is generated on first view.

When we click on email button it goes to controllers then model and so on.

I want to access the HTML of first view in controller or model so that i can send it in email.

I don't have any clue that how we can do it in MVC.

Can anyone tell me what's the best way to achieve this task.

Code Rider
  • 2,003
  • 5
  • 32
  • 50

2 Answers2

0

you need to regenerate HTML to send first view by email , so you can use ViewEngines.Engines.FindView to get your view and then render it using View.Render then send it by email.

Mah3
  • 83
  • 8
0

Extract the email template into a partial view (so you could reuse it), then you can render the partial view into a string in the controller action so you could use it as email body:

This method taken from Render a view as a string will allow you to render partial view into a string:

public string RenderRazorViewToString(string viewName, object model)
{
  ViewData.Model = model;
  using (var sw = new StringWriter())
  {
    var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,
                                                             viewName);
    var viewContext = new ViewContext(ControllerContext, viewResult.View,
                                 ViewData, TempData, sw);
    viewResult.View.Render(viewContext, sw);
    viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
    return sw.GetStringBuilder().ToString();
  }
}

In the controller action that should send an email you can do something like this:

public ActionResult SendEmail(SomeModel model)
{
    //generate a model for an email:
    var emailModel = ....;

    //assuming that _EmailTemplate.cshtml is a partial view that contains the email template
    var emailBody = this.RenderRazorViewToString("_EmailTemplate",emailModel);

    //send the email here...
}
Community
  • 1
  • 1
Alex Art.
  • 8,711
  • 3
  • 29
  • 47