views:

94

answers:

1

I use ASP.NET MVC with jQuery and have a lot of Ajax requests to my controllers.

Use Partial Views (usercontrols) to build the intial view when a page is loaded. Then if I need to append/replace data based on my Ajax request I build HTML from the Json response.

This approach gives me full control, ie. I can get extra information back from my controller if something went wrong, and then show an error message based on that.

However, recently I've been really annoyed with all the extra work that goes into maintaining HTML structure both in my partial views and the part that generates HTML from Json.

I like to make a jQuery ajax request and then have the controller return PartialView("mypartialview") and then just use jQuery to replace to HTML in the view.

However, this way I cannot attach extra data from the controller - it's either whatever the partial view gives me - or nothing. At least that's my current take on it.

If some validation goes wrong at some point in my controller action I don't want to return the HTML of the partial view.

So how do you go about handling this issue?

Thanks for reading.

+1  A: 

I believe you could return the rendered html as a string - this could alternately be an html string containing an error message to display?

Paddy
Indeed, that is just what a PartialView response is. And though you don't quite spell it out, this is the solution: Have your AJAX methods return a rendered PartialView using the same user control you used to render that portion of the page initially. You do this by writing return PartialView(model) instead of return Json(model).
Craig Stuntz
Thanks. That is indeed a better explanation :)
Paddy
Craig, that is what I do now. My problem is that I want to return both Html and Json - or to put otherwise: I want the resulting html that is returned from return PartialView and then wrap in Json, so that I can send along other data as well.Kind of like this guy:http://stackoverflow.com/questions/1168791/returning-a-rentered-html-partial-in-a-json-property-in-asp-net-mvcI guess the above would work, but I'd like to know how others handle this.
bgeek
You can (easily) return the same model as either a partial view (HTML fragment) or JSON. Build the model, then call whichever method you need. But don't write JavaScript which duplicates your partial view from a JSON serialization of the same model.
Craig Stuntz