What is the best way to return JSON * and * HTML to the same ActionResult in ASP.NET MVC

I use ASP.NET-MVC and return JSON or HTML from my MVC actions.

I came across some cases where I need to return BOTH JSON and HTML at the same time. For example, I can update the shopping cart and you need to return the HTML view as well as the updated JS object model.

I found a lot of questions about when to return an answer such as an answer, but no one talks about how to return both.

Is there a reliable way to do this? It should work in browsers without any extra thoughts.

  • multi-part answer?
  • JSON encoded HTML?
  • A script tag embedded in HTML containing JSON that runs a function to update the object model. I am inclined to this method, but I am worried that scripts can be reliably launched when adding them to the DOM using html ("...")
  • in any other way?

If this is not the case, I just need to make 2 requests to get HTML and then JSON.

+4
source share
3 answers
an HTML representation as well as an updated JS object model 

If you use HTML and JS to update the same part of a view, then consider HTML encoded as a JSON result. If you are trying to update different parts of a presentation, I will use two methods of action to follow the โ€œsingle responsibilityโ€ rule.

+2
source

To return a multi-part body, you can package the response inside the MIME container. But this will make the reaction unsuitable for most customers.

I usually put html in the JSON result.

+1
source

There are two alternatives that I use.

  • Return the HTML and put the json object in the "data" attribute of the hidden range or hidden input value. 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 that you will return from AJAX, and call the existing function from this script. There is a reliable way to manage this. You can always find script tags in your html and evaluate them using eval ().

0
source

All Articles