Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP MVC View Content as JSON

I have a MVC app with quite a few Controller Actions that are called using Ajax (jQuery) and return partial views content which updates a part of the screen. But what I would rather do is return JSON something like this.

return Json(new { 
    Result = true, 
    Message = "Item has been saved", 
    Content = View("Partial") 
});

Where the HTML is just a property of the Json. What this means is I need to retrieve the HTML that is rendered by the View method. Is there any easy way to do this, a few examples I have seen are quite convoluted.

Edit: This question was originally for ASP.NET MVC 1, but if version 2 makes it easier I would like to hear the answer.

like image 412
Craig Avatar asked May 26 '09 00:05

Craig


People also ask

How do I return JSON data and view?

JSON you are returning contains 4 properties, the way you are accessing isValid , similarly access the View . $. ajax({ type: "GET", url: "/serviceentry/getservice", data: ({ "SONumber": soNumber }), success: function (data) { if (data. isValid) { //Element- Where you want to show the partialView $(Element).

How pass JSON data in MVC?

1) Create an attribute that overrides the OnActionExecuting event handler. 3) use attribute parameters to figure out the type of object you want to stream the data into. 4) deserialize the JSON object into your object.


2 Answers

Here is the answer! It is slight change from Martin From's method and it seems to work. If there are things missing please can people contribute any code changes in the comments section. Thanks.

From you controller call it like this:

string HTMLOutput = Utils.RenderPartialToString("~/Views/Setting/IndexMain.ascx", "", items, this.ControllerContext.RequestContext);

Add this to a class

public static string RenderPartialToString(string controlName, object viewData, object model, System.Web.Routing.RequestContext viewContext)
{
     ViewDataDictionary vd = new ViewDataDictionary(viewData);
     ViewPage vp = new ViewPage { ViewData = vd };

     vp.ViewData = vd;
     vp.ViewData.Model = model;
     vp.ViewContext = new ViewContext();
     vp.Url = new UrlHelper(viewContext);

     Control control = vp.LoadControl(controlName);

     vp.Controls.Add(control);

     StringBuilder sb = new StringBuilder();

     using (StringWriter sw = new StringWriter(sb))
     using (HtmlTextWriter tw = new HtmlTextWriter(sw))
     {
         vp.RenderControl(tw);
     }

     return sb.ToString();
}
like image 56
Jon Avatar answered Nov 30 '22 23:11

Jon


NerdDinner has some pretty good examples of this. Here is the SearchController in NerdDinner, which has a method called SearchByLocation that returns a list of JsonDinners (source code for NerdDinner is Creative Commons):

namespace NerdDinner.Controllers {

    public class JsonDinner {
        public int      DinnerID    { get; set; }
        public string   Title       { get; set; }
        public double   Latitude    { get; set; }
        public double   Longitude   { get; set; }
        public string   Description { get; set; }
        public int      RSVPCount   { get; set; }
    }

    public class SearchController : Controller {

        IDinnerRepository dinnerRepository;

        //
        // Dependency Injection enabled constructors

        public SearchController()
            : this(new DinnerRepository()) {
        }

        public SearchController(IDinnerRepository repository) {
            dinnerRepository = repository;
        }

        //
        // AJAX: /Search/FindByLocation?longitude=45&latitude=-90

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult SearchByLocation(float latitude, float longitude) {

            var dinners = dinnerRepository.FindByLocation(latitude, longitude);

            var jsonDinners = from dinner in dinners
                              select new JsonDinner {
                                  DinnerID = dinner.DinnerID,
                                  Latitude = dinner.Latitude,
                                  Longitude = dinner.Longitude,
                                  Title = dinner.Title,
                                  Description = dinner.Description,
                                  RSVPCount = dinner.RSVPs.Count
                              };

            return Json(jsonDinners.ToList());
        }
    }
}
like image 32
Robert Harvey Avatar answered Dec 01 '22 01:12

Robert Harvey