Generate html from razor template in controller

2019-09-02 04:08发布

I need to use the html generated by a razor template in one of my controllers, an abstract one actually to handle ajax lists. That way I can have a generic ajax list implementation which will work for any type of model, and provide the standard operations like add/edit/delete ...

Since I'd like to generate the list elements on the server, I thought I could make razor templates for each element, and then return the generated html (for a new element, or for editing an element) in a JSON object like this:

  • a flag to tell if the operation was successful
  • an error field to describe the error (if there was one)
  • the generated html

At first I thought about instantiating an HtmlHelper (as explained here: HtmlHelper in controller) and using the EditorFor method, but I'm wondering if this a good way to achieve this, since creating an instance of HtmlHelper seems to be quite a time consuming operation.

Is there a simple way to execute the right razor template and get the html in a string?

Also is there a better way to implement such a generic behavior?

1条回答
▲ chillily
2楼-- · 2019-09-02 04:53

I created a method that does the trick. My reason for creating the method was the same as yours; I wanted to return a JsonResult that contained not only the markup but some other data as well.

public string RenderPartialViewToString(string viewName, object model, ViewDataDictionary viewData = null)
{
    ViewData.Model = model;

    if (viewData != null)
        foreach (KeyValuePair<string, object> item in viewData)
            ViewData.Add(item);

    using (var sw = new System.IO.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();
    }
}

I placed this method in my base controller so all my controllers have access to it.

查看更多
登录 后发表回答