Alex F
Alex F

Reputation: 27

How to pass the data recieved via AJAX to ASP MVC partial views?

What I'm trying to achieve is to update some part of a page containing partial views. My attempt on doing so is below:

        $.ajax({
        type: 'GET',
        url: actionUrl,
        success: function (data) {
            $("#results").html(""); 
            $("#results").append(@Html.Partial("_FirstPartial", data.FirstDataSet));
            $("#results").append(@Html.Partial("_SecondPartial", data.SecondDataSet));    
            }
        });

Of course I couldn't pass JS variables to ASP MVC methods like that, so how could I? Or probably there is a completely different, better approach for the way I could update the page?

Upvotes: 0

Views: 919

Answers (2)

Paweł Mikołajczyk
Paweł Mikołajczyk

Reputation: 381

Make in your controller method which returns partial you want, then in your Index.cshtml file make something like this:

<script>
  var Services = {
    linkToPartial: '@Url.Action('MethodName', 'Controller')'
  }
</script>

This code will provide an action link which you can use in your $ajax success method and provide arguments.

$("#results").html("");
$.ajax({
  method: 'GET',
  url: Services.linkToPartial,
  data: {
    argumentName: data.FirstDataSet
  }
}).done(function (html) {
  $('#results').append(html);
});

Upvotes: 0

Mahmood Dehghan
Mahmood Dehghan

Reputation: 8265

View (Javascript):

$.ajax({
    type: 'GET',
    url: actionUrl,
    success: function (data) {
        $("#results").html(""); 
        $.post('@Url.Action ("FirstPartial")',{data:data.FirstDataSet},function(ret){
            $("#results").append(ret);
            $.post('@Url.Action ("SecondPartial")',{data:data.SecondDataSet},function(ret2){
                $("#results").append(ret2);
            }
        }
    }
});

Controller:

public ActionResult FirstPartial(string data)
{
    return PartialView("_FirstPartial", data);
}
public ActionResult SecondPartial(string data)
{
    return PartialView("_SecondPartial", data);
}

You need to use Partial Actions (that returns a partial view). In javascript, after getting datasets you call another partial action to render datasets.

I nested two ajax calls to render the second view below the first view. If you remove the nesting then the second one may render before the first one.

Upvotes: 2

Related Questions