Can a Web Api controller render a view as a string?

前端 未结 1 454
慢半拍i
慢半拍i 2021-01-29 01:53

I would like to write a Web Api controller action that would send an email depending on results. I would like to use an MVC View or Partial view with a model of data to render t

相关标签:
1条回答
  • 2021-01-29 02:40

    If you don´t want to go with the RazorEngine approach suggested in the comments, you could define a class like this:

    public static class ViewUtil
    {
        public static string RenderPartial(string partialName, object model)
        {
            var sw = new StringWriter();
            var httpContext = new HttpContextWrapper(HttpContext.Current);
    
            // point to an empty controller
            var routeData = new RouteData();
            routeData.Values.Add("controller", "EmptyController");
    
            var controllerContext = new ControllerContext(new RequestContext(httpContext, routeData), new EmptyController());
    
            var view = ViewEngines.Engines.FindPartialView(controllerContext, partialName).View;
    
            view.Render(new ViewContext(controllerContext, view, new ViewDataDictionary { Model = model }, new TempDataDictionary(), sw), sw);
    
            return sw.ToString();
        }
    }
    
    class EmptyController : Controller { }
    
    0 讨论(0)
提交回复
热议问题