I am using asp.net mvc 3 and have strongly typed models to pass to. The models will accept data if it is in a proper form. This form dictates that the data be in NameMatchingModel=value separated by &. For example, if I had:
viewmodel:
public class CarViewModel
{
public Car Car { get; set; }
}
public class Car
{
public string Make { get; set; }
public string Model { get; set; }
}
and then I had a method accepting this ViewModel
public ActionResult AcceptCarVM( CarViewModel model )
{
//TODO: use car data
return View();
}
Now, I want to pass in the viewmodel filled with some details for the car. Is there a better approach to doing this than this manual way?
var carMake = "Ford";
var carModel = "Pinto";
var viewModelData = "Car.Make=" + carMake + "&Car.Model=" + carModel;
var encodeData = encodeURIComponent(viewModelData);
$.ajax({
url: "@(Url.Action("AcceptCarVM"))",
type: 'GET',
data: encodeData,
success: function (result) {
//TODO: use result
}
});
jQuery has a function to serialize query strings
Here’s the documentation
You will of course provide your data in a different manner… But since you’re nesting types I could suggest to use the .toDictionary plugin that will correctly serialize JSON objects regardless of their structure, and also convert dates in a way that Asp.net MVC will understand when data binding.
or even:
The second one is especially useful when you have a controller action that takes two parameters of the same type, so you can provide root object’s name the same as action parameter names, so they’ll get correctly data bound on the server side ie:
Plugin internally uses jQuery functionality so it serializes things reliably and is especially suited for Asp.net MVC back-end.