asp.net-mvcpartial-views

How to Render Partial View into a String


I have the following code:

public ActionResult SomeAction()
{
    return new JsonpResult
    {
        Data = new { Widget = "some partial html for the widget" }
    };
}

I'd like to modify it so that I could have

public ActionResult SomeAction()
{
    // will render HTML that I can pass to the JSONP result to return.
    var partial = RenderPartial(viewModel); 
    return new JsonpResult
    {
        Data = new { Widget = partial }
    };
}

is this possible? Could somebody explain how?

note, I edited the question before posting the solution.


Solution

  • This is a slightly modified version of an answer that works:

    public static string RenderPartialToString(string controlName, object viewData)
    {
        ViewPage viewPage = new ViewPage() { ViewContext = new ViewContext() };
    
        viewPage.ViewData = new ViewDataDictionary(viewData);
        viewPage.Controls.Add(viewPage.LoadControl(controlName));
    
        StringBuilder sb = new StringBuilder();
        using (StringWriter sw = new StringWriter(sb))
        {
            using (HtmlTextWriter tw = new HtmlTextWriter(sw))
            {
                viewPage.RenderControl(tw);
            }
        }
    
        return sb.ToString();
    }
    

    Usage:

    string ret = RenderPartialToString("~/Views/MyController/MyPartial.ascx", model);