2012-10-30 64 views
0

我有一个网格控件,我已经绑定到一个IEnumerable模型。如何在我的控制器我想保存一个记录。我正在使用的网格控件是Telerik'Kendo'中的一个。请求返回是一个字符串,我希望获得绑定对象'CustomerViewModel',当我传入对象时它会返回null。我尝试过不同类型的信息,它似乎只适用于指定我想要传递的属性。请在下面找到代码并提供帮助?将查询字符串绑定到ASP.NET MVC中的对象?

[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()); 
     } 
+0

你可以发布你的观点代码 – Raymund

回答

2

如果对象被嵌入到查询字符串中,MVC将始终将其视为字符串。

你需要做这样的事情:

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()); 
    } 

我已经有类似的东西,我不能做一个Ajax获取或张贴在那里你可以在内容类型设置为JSON挣扎。似乎没有办法做到这一点在查询字符串(这是有道理的,因为它只是一个字符串)。

反序列化它在控制器中似乎是唯一的选择。很想听到一个能够表现出完美的方式的人。

相关问题