jaap jaap - 4 months ago 34
Ajax Question

ASP.NET MVC Load page with AJAX

I have this situation:

A page with an accordion with 2 tabs, one has a list of paymentmethods, the second has a summary of the order with orderlines, amounts and totals (rendered as partialview). Selecting a paymentmethod causes the order totals to be recalculated, extra costs etc might apply.

What is the recommended way to display the new ordersummary after a paymentmethod is selected, using AJAX?

Doing an AJAX call and getting all the new amounts, orderlines, etc and setting these values using JS seems inefficient to me. Ideal situation would be if I could make an AJAX call with the selected payement method and this call would return the HTML which I can use to replace the old summary.

Is it bad to render a partialview to HTML on the server and return it using JSON? What is best practice for this situation?


In your action method return a PartialView([view name]).

Then you can do this with jquery:

var req = $.ajax({
  type:"GET",//or "POST" or whatever
  url:"[action method url]"

Where 'targetelement' is a selector for the element into which you want to inject the content.

You might want to do $('targetelement').html(''); first before appending the response to the target element.


Or, better yet, use .load from Rick's answer.