BoundForGlory BoundForGlory - 6 months ago 13
Javascript Question

Update multiple DOM elements by making only one call to ActionResult

I have to update multiple DOM elements (in this case divs) when I make a certain call in my MVC3 application. All of my Action results are in separate functions all with their own view models:

public ActionResult Action3(ViewModel3 model)
{
return PartialView("_DomElement3", model);
}

public ActionResult Action2(ViewModel2 model)
{
return PartialView("_DomElement2", model);
}

public ActionResult Action1(ViewModel1 model)
{
return PartialView("_DomElement1", model);
}


Here's what all three razor partial views look like (just with different models):

@model ViewModel1
<div id='domElement1'>@Model.values1</div>


I did it this way because they were being called on demand and I thought nothing else would trigger them. But I ran across a scenario where I will have to update all three of my div elements after a certain criteria is met. I'm currently doing it this way and I don't like it one bit:

var values_1 = {'values1':'one'};
$.ajax({
url: '@Url.Action("Action1")',
dataType: 'json',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: values_1,
success: function (data) {
$('#domElement1').html(data);
var values_2 = {'values2':'two'};
$.ajax({
url: '@Url.Action("Action2")',
dataType: 'json',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: values_2,
success: function (data) {
$('#domElement2').html(data);
var values_3 = {'values3':'three'};
$.ajax({
url: '@Url.Action("Action3")',
dataType: 'json',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: values_3,
success: function (data) {
$('#domElement3').html(data);

}
});

}
});

}
});


As you can see, I'm making calls to the server one at a time. Does anyone know a better way to update my elements with only one call to the server?

Answer

I'd have to build a sample app to test it, but one possibility is to have a method that returns JSON. This response could return an array of partial results:

[HttpPost]
public ActionResult SomeMethodName()
{
    /* get your data */

    var results = new List<ActionResult>();

    foreach(var model in YourCollection)
    {
        results.Add(new PartialResult("viewname", mode));
    }

    return Json(results.ToArray());
}

This is pretty much pseudo code, but should get the point across.