Alex F Alex F - 3 months ago 14
Ajax Question

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?

Answer

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.