Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

webapi render model as html within the controller

I have a webapi controller action which creates an html email. currently i'm using string.format to create the html, as it's the simplest possible thing. I know this will become more complex moving forward and would like to use razor templating.

I have seen examples of how to do this for MVC controllers, but I cannot find any for how to do this within a WebApiController. Is this possible? If so do you know of any resources? My google-fu is failing me.

like image 637
Jason Meckley Avatar asked Jan 15 '23 22:01

Jason Meckley


2 Answers

Checkout this article Rendering an ASP.NET MVC View to a string in a Web Api Controller by Wouter de Kort

 public static string RenderViewToString(string controllerName, string viewName, 
                                         object viewData)
{
    HttpContextBase contextBase = new HttpContextWrapper(HttpContext.Current);

    var routeData = new RouteData();
    routeData.Values.Add("controller", controllerName);
    var controllerContext = new ControllerContext(contextBase, routeData, 
                                                   new EmptyController());

    var razorViewEngine = new RazorViewEngine();
    var razorViewResult = razorViewEngine.FindView(controllerContext, viewName, 
                                                     "", false);

    var writer = new StringWriter();
    var viewContext = new ViewContext(controllerContext, razorViewResult.View, 
           new ViewDataDictionary(viewData), new TempDataDictionary(), writer);
    razorViewResult.View.Render(viewContext, writer);

    return writer.ToString();
}

private class EmptyController : ControllerBase
{
    protected override void ExecuteCore() { }
}

//You can simply call this from anywhere in your Web Api Controller: 

RenderViewToString("controller", "view", model)
like image 196
Stefan P. Avatar answered Jan 19 '23 00:01

Stefan P.


I've been using this ViewRenderer class with great success:

https://github.com/RickStrahl/WestwindToolkit/blob/master/Westwind.Web.Mvc/Utils/ViewRenderer.cs

Call it like this:

var html = ViewRenderer.RenderView("~/views/emails/ActivationEmail.cshtml", emailModel);
like image 43
perfect_element Avatar answered Jan 19 '23 00:01

perfect_element