Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 794
jaap Avatar asked Oct 05 '11 13:10

jaap


2 Answers

I have an example here:

Javascript

$("#divForPartialView").load("/HelloWorld/GetAwesomePartialView",
   { param1: "hello", param2: 22}, function () {
   //do other cool client side stuff
});

Controller Action

public ActionResult GetAwesomePartialView(string param1, int param2)
{
    //do some database magic
    CustomDTO dto = DAL.GetData(param1, param2);

    return PartialView("AwesomePartialView",dto);
}
like image 136
rick schott Avatar answered Nov 19 '22 12:11

rick schott


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]"
  }).success(function(responseData){
    $('targetelement').append($(responseData));});

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.

Update

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

like image 2
Andras Zoltan Avatar answered Nov 19 '22 14:11

Andras Zoltan