Binding query string to object in ASP.NET MVC?

五迷三道 提交于 2019-12-25 02:24:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!