Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a rendered HTML partial in a JSON Property in ASP.NET MVC

I've been happily returning JsonResult objects or partial ASP.NET views from my controllers in ASP.NET.

I would like to return a rendered partial view as a property in a JSON object. e.g.

requesting

/post/detail/1

would return

{"PostId": 1, "Html": "<p>some markup rendered from a partial to inject</p>" }

This would allow me to know the PostId when I am handling the response in JavaScript. Any tips on the best way to do this?

like image 899
Lance Fisher Avatar asked Dec 17 '22 06:12

Lance Fisher


2 Answers

Here is some code that will work cause I needed to do this today. The original code is described here.

public static string RenderPartialToString(string controlName, object viewData)
{
    var viewContext = new ViewContext();
    var urlHelper = new UrlHelper(viewContext.RequestContext);
    var viewDataDictionary = new ViewDataDictionary(viewData);

    var viewPage = new ViewPage
    {
        ViewData = viewDataDictionary,
        ViewContext = viewContext,
        Url = urlHelper
    };

    var control = viewPage.LoadControl(controlName);
    viewPage.Controls.Add(control);

    var sb = new StringBuilder();
    using (var sw = new StringWriter(sb))
    using (var tw = new HtmlTextWriter(sw))
    {
            viewPage.RenderControl(tw);
    }

    return sb.ToString();
}

You can then use it to do RJS style json results

public virtual ActionResult Index()
{
    var jsonResult = new JsonResult
    {
        Data = new
        {
            main_content = RenderPartialToString("~/Views/contact/MyPartial.ascx", new SomeObject()),
            secondary_content = RenderPartialToString("~/Views/contact/MyPartial.ascx", new SomeObject()),
        }
    };

    return Json(jsonResult, JsonRequestBehavior.AllowGet);
}

And the partial has a strongly typed view model

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<SomeObject>" %>
<h1>My Partial</h1>
like image 108
superlogical Avatar answered May 21 '23 13:05

superlogical


Something like:

return new JsonResult { Data = new { PostId = 1; Html = "<p>some markup rendered from a partial to inject</p>" } };
like image 28
rball Avatar answered May 21 '23 15:05

rball