Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net MVC: Send back HTML inside Json object

I want to return back html inside my json object however this does not seem to work, my code:

return new JsonResult()
{
 Data = new { Error = false, NewComment = PartialView("Review/InlineCommentUC", dto) }
};

I want NewComment to have some html inside it...

What I recieve (using firebug) for the NewComment object in json format is:

TempData = []
View = null,
ViewData = []
ViewEngineCollection = some data..
ViewName = name of view

I am using Jquery to render the output onto the html, the reason for sending back a json object is, so I can handle my errors very easily.

Ideally a custom Action Result is what I am looking for...

like image 219
Haroon Avatar asked Nov 22 '11 13:11

Haroon


1 Answers

Is http://craftycodeblog.com/2010/05/15/asp-net-mvc-render-partial-view-to-string/ what you're looking for?

Copied using the WayBackMachine.

I have run into a situation where I would like to render a partial view to a string and then return it as part of a JSON response like so:

return Json(new {
    statusCode = 1,
    statusMessage = "The person has been added!",
    personHtml = PartialView("Person", person)
});

The ability to do something like this would open up a ton of amazing possibilities, so I really scoured the internet looking for a solution. Unfortunately, no one seems to have come up with a clean solution for it, so I dug into the MVC code and came up one…and because I’m such a nice guy, you get to copy it for free. ;)

public abstract class MyBaseController : Controller {

    protected string RenderPartialViewToString()
    {
        return RenderPartialViewToString(null, null);
    }

    protected string RenderPartialViewToString(string viewName)
    {
        return RenderPartialViewToString(viewName, null);
    }

    protected string RenderPartialViewToString(object model)
    {
        return RenderPartialViewToString(null, model);
    }

    protected string RenderPartialViewToString(string viewName, object model)
    {
        if (string.IsNullOrEmpty(viewName))
            viewName = ControllerContext.RouteData.GetRequiredString("action");

        ViewData.Model = model;

        using (StringWriter sw = new StringWriter()) {
            ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
            ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
            viewResult.View.Render(viewContext, sw);

            return sw.GetStringBuilder().ToString();
        }
    }
}

Now you can simply do this:

public class MyController : MyBaseController {

    public ActionResult CreatePerson(Person p) {
        if (ModelState.IsValid) {
            try {
                PersonRepository.Create(p);
                return Json(new {
                    statusCode = 1,
                    statusMessage = "The person has been added!",
                    personHtml = RenderPartialViewToString("Person", p)
                });
            }
            catch (Exception ex) {
                return Json(new {
                    statusCode = 0,
                    statusMessage = "Error: " + ex.Message
                });
            }
        }
        else
            return Json(new {
                statusCode = 0,
                statusMessage = "Invalid data!"
            });
    }
}

Also note that you can modify these functions to render a View (rather than a PartialView) with this small change:

ViewEngineResult viewResult = ViewEngines.Engines.FindView(ControllerContext, viewName);

Enjoy!

like image 59
JesseBuesking Avatar answered Sep 19 '22 12:09

JesseBuesking