Last night I tried to put together something that I have had working since MVC2.
Given the following class:
public class RouteSaveViewModel
{
public string Title { get; set; }
public string Comments { get; set; }
public string DepartureDate { get; set; }
public string ArrivalDate { get; set; }
public List<int> LocationIds { get; set; }
}
…and the action below:
[HttpPost]
public ViewResult SaveRoute(RouteSaveViewModel route)
{
// yada yada
return SomethingShiny();
}
I would like to pass in the data using a $.ajax or $.post. The form is multi-step to collect data from the user and submit it. The code I use to build the location Ids up is this:
var routeStopIds = [];
$(".route-stop").each(function(){
routeStopIds.push($(this).attr('data-id'));
});
I have verified that there the ids I expect are in this array through in-browser dev tools and fiddler. Finally, to submit the data, I’m mapping out the object as I’ve done in previous MVC builds:
$.ajax({
type: 'post',
url: postUrl,
data: {
Title: $("#route-title").val(),
Comments: $("#route-description").val(),
DepartureDate: depDate,
ArrivalDate: arrDate,
LocationIds: routeStopIds
},
dataType: 'JSON'
});
What I’m seeing is that all data – except the LocationIds param is populated. I have also tried to submit just the routeStopIds array to a modified SaveRoute that only accepts a List<int> and that doesn’t appear to be working either. Either way, LocationIds is null, though there is a form-encoded value in the form parameters on the request.
{LocationIds%5b%5d=44&LocationIds%5b%5d=4&LocationIds%5b%5d=2}
…and yet the HttpValueCollection is just LocationIds[], an empty array.
So, am I missing something obvious? Maybe not-so-obvious? How do I get the array to be picked up by model binding?
Remember that part where I said I had it working since MVC2? Yeah, that was here:
Advanced Model Binding In that post I explicitly mentioned the following:
Modifying the ajax call to include this setting was the fix. All is right as rain and soft woolen kittens. Or mittens or whatever.