Whats the best way to return JSON *and* HTML in same ActionResult in ASP.NET MVC
I'm using ASP.NET-MVC and returning JSON or HTML from my MVC actions.
I've come across some cases where I need to return BOTH JSON and HTML at the same time. For instance I may update a shopping cart and need to return an HTML representation as well as an updated JS object model.
I've found a lot of questions on SO about when to return which type of response, but none talking about how to return both.
Is there a reliable way of doing this? Must work across browsers without any extra thought.
- multi-part response?
- HTML encoded in the JSON result?
- some kind of script tag embedded in the HTML containing JSON that would run a function to update the object model. i'm leaning towards this method, but concerned that scripts may not reliably开发者_C百科 be run when adding them to the DOM with html("...")
- some other way?
If theres not a good way I'll just have to make 2 requests to get the HTML and then the JSON.
an HTML representation as well as an updated JS object model
If you are using HTML and JS to update the same portion of the view, then consider HTML encoded in the JSON result. If you are trying to update different portions of the view, then I will use two action methods to follow "single responsibility" rule.
To return a multipart body, you could pack the response inside a MIME container. But that would make the response unusable by most clients.
I usually put html inside the JSON result.
There are two alternatives I use
Return HTML and put the json object to a "data" attribute of a hidden span, or value of a hidden input. In your ajax success method, get the object from there.
<span id='response-message' data-result='@Html.Raw(JsonConvert.SerializeObject(Model.ComplexProperty))' />
$.post(url, function(resp,st) { if ( st == 'success' ) { var result = $('#response-message').data('result); if ( result ) { } } });
Put the Javascript in the partial HTML you return from AJAX and call an existing function from within that script. There is a reliable way of running this. You can always find the script tags in your html and evaluate them with eval().
精彩评论