0

I need to create the body of a email in html format. Inside a HistoryController I define a metod that return an object (Course) which attributes will be used for crate the body as i said. I dont know how to get the object in the View. I've seen a metod using ActionResult but i dont to present the View it just work like an auxiliary for creating the email.

I get this.

HistoryController

public static CURSO courseSelected = new CURSO();
public static CURSO courseSel()
{
    courseSelected.Name = "Physics";
    return courseSelected;//cursoSelected del tipo CURSO
}

View

@model Project.Models.Course
@{ 
    var courseSel = Project.Models.HistoryController.courseSel(); 
}
<fieldset class="fHorizontalCenter">
        <label style="font-size:18px">Welcome to course of </label><label>@courseSel.Name</label>< br />
</fieldset>

But i cant use de data of the variable, It always prints this

Welcome to course of @courseSel.Name

Kevtho
  • 193
  • 1
  • 9

1 Answers1

0

Let's say you have a model that looks like this:

namespace Project.Models
{
    public class Course
    {
        public string CourseName { get; set; }
    }
} 

and a view named "CourseEmailTemplate.cshtml" in your Views/Shared Folder:

@model Project.Models.Course
@{
    Layout = null;
}

<fieldset class="fHorizontalCenter">
    <label style="font-size:18px">Welcome to course of </label><label>@Model.CourseName</label>< br />
</fieldset>

then the controller could look something like this:

public class HistoryController : Controller
 {
    public ActionResult Index(/*put whatever parameters in here*/)
    {
       // Fetch your model 
       // just example data
       var course = new Course { CourseName = "your coursename" };

       var html = GetEmailText(course);

        // send your email

        return View(); // or redirect to action
    }

    private string GetEmailText(Course course)
    {
        return RenderRazorViewToString("CourseEmailTemplate", course);
    }

    private 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();
        }
    }
}

some code stolen from Render a view as a string

Florian Schmidinger
  • 4,682
  • 2
  • 16
  • 28