Thursday, 31 December 2015

Render RazorView to string



public ActionResult GetHtmlAction()
{
    string HtmlContent = RenderRazorViewToString("ConvertToIntPartialView", 45.59);
    return Content(HtmlContent);
}



using System.IO;

public string RenderRazorViewToString(string viewName, object model)
{
    string RetVal = string.Empty;

    try
    {
        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);

            RetVal = sw.GetStringBuilder().ToString();
        }
    }
    catch (Exception ex)
    {              
    }

    return RetVal;
}




No comments:

Post a Comment