问题
I have a grid control that I have bound to a model of IEnumerable. How ever in my controller I would like to save a record. The grid control I am using is one from Telerik 'Kendo'. The request back is a string and I would like to get my bound object 'CustomerViewModel' how ever when I pass in my object it comes back null. I have tried different types of information and it seems to only work for i specify the property I would like to pass in. Please find code below and assist?
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Save([DataSourceRequest] DataSourceRequest request, CustomerViewModel customerViewModel)
{
if (customerViewModel != null && ModelState.IsValid)
{
var customers = Repository.GetItems<Customer>();
Repository.SaveChanges<Customer, CustomerViewModel, NorthWindDataContext>(customers, customerViewModel);
}
return Json(ModelState.ToDataSourceResult());
}
回答1:
If the object is embedded in the query string, MVC will always see it as a string.
You would need to do something like this:
public ActionResult Save(string customerViewString)
{
var jsonSerializer = new JavaScriptSerializer();
var customerViewModel = jsonSerializer.Deserialize<CustomerViewModel>(customerViewString);
if (customerViewModel != null && ModelState.IsValid)
{
var customers = Repository.GetItems<Customer>();
Repository.SaveChanges<Customer, CustomerViewModel, NorthWindDataContext>(customers, customerViewModel);
}
return Json(ModelState.ToDataSourceResult());
}
I have been struggling with something similar where I can't do an Ajax Get or Post where you can set the content type to JSON. There seems to be no way of doing that in the query string (which does make sense as its just a string).
De-Serializing it in the controller seems like the only option. Would love to hear from someone who can show a neater way of doing this.
来源:https://stackoverflow.com/questions/13145160/binding-query-string-to-object-in-asp-net-mvc