How to render a Razor View to a string in ASP.NET

2019-01-03 16:29发布

I've been searching the site a lot, but all I could find were examples on how to render partial controls .ascx, or depended on a controller context.

I want a method that enables me to provide just the relative path to the view, and a model, and render that view with that model into a string:

string result = Utility.RenderViewToString("~/Views/My/Profile.cshtml", model);

All the examples I could find were either for older versions of MVC, or simply didn't do what I need to do here.

4条回答
Melony?
2楼-- · 2019-01-03 17:12

I had created solution for me. It's Extension that render view into string.

public static class RenderPartialToStringExtensions
{
    /// <summary>
    /// render PartialView and return string
    /// </summary>
    /// <param name="context"></param>
    /// <param name="partialViewName"></param>
    /// <param name="model"></param>
    /// <returns></returns>
    public static string RenderPartialToString(this ControllerContext context, string partialViewName, object model)
    {
        return RenderPartialToStringMethod(context, partialViewName, model);
    }

    /// <summary>
    /// render PartialView and return string
    /// </summary>
    /// <param name="context"></param>
    /// <param name="partialViewName"></param>
    /// <param name="viewData"></param>
    /// <param name="tempData"></param>
    /// <returns></returns>
    public static string RenderPartialToString(ControllerContext context, string partialViewName, ViewDataDictionary viewData, TempDataDictionary tempData)
    {
        return RenderPartialToStringMethod(context, partialViewName, viewData, tempData);
    }

    public static string RenderPartialToStringMethod(ControllerContext context, string partialViewName, ViewDataDictionary viewData, TempDataDictionary tempData)
    {
        ViewEngineResult result = ViewEngines.Engines.FindPartialView(context, partialViewName);

        if (result.View != null)
        {
            StringBuilder sb = new StringBuilder();
            using (StringWriter sw = new StringWriter(sb))
            {
                using (HtmlTextWriter output = new HtmlTextWriter(sw))
                {
                    ViewContext viewContext = new ViewContext(context, result.View, viewData, tempData, output);
                    result.View.Render(viewContext, output);
                }
            }

            return sb.ToString();
        }
        return String.Empty;
    }

    public static string RenderPartialToStringMethod(ControllerContext context, string partialViewName, object model)
    {
        ViewDataDictionary viewData = new ViewDataDictionary(model);
        TempDataDictionary tempData = new TempDataDictionary();
        return RenderPartialToStringMethod(context, partialViewName, viewData, tempData);
    }
}

And than we can render view in Action

[HttpPost]
public ActionResult GetTreeUnit(string id)
{
    int _id = id.ExtractID();
    string render = ControllerContext.RenderPartialToString("SomeView");
    return Json(new { data = render });
}
查看更多
等我变得足够好
3楼-- · 2019-01-03 17:12

Though Marc's is answer is correct and works for previous versions. But that is now obselete and needs to be replaced.

Here is the new code that worked for me and you can find more useful information on Github : Razor Engine

string template = "Hello @Model.Name! Welcome to Razor!";
string Result = Engine.Razor.RunCompile(template, "templateKey", null, new { Name = "World" });
查看更多
Viruses.
4楼-- · 2019-01-03 17:18

You can achieve that with the razorengine.

string template = "Hello @Model.Name! Welcome to Razor!";
string result = Razor.Parse(template, new { Name = "World" });

And it does not rely on the controller context - but because of that you are not able to use the Html helpers (which rely on the http context). But it is perfect to use razor as a template engine for strings.

查看更多
趁早两清
5楼-- · 2019-01-03 17:29

You can check this link.

extracted content From Render Razor view to String. .

public static 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);
        return sw.GetStringBuilder().ToString();
    }
}
查看更多
登录 后发表回答