简体   繁体   English

将查询字符串绑定到ASP.NET MVC中的对象?

[英]Binding query string to object in ASP.NET MVC?

I have a grid control that I have bound to a model of IEnumerable. 我有一个网格控件,我已绑定到IEnumerable的模型。 How ever in my controller I would like to save a record. 在我的控制器中我想保存一条记录。 The grid control I am using is one from Telerik 'Kendo'. 我正在使用的网格控件来自Telerik的“剑道”。 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. 请求返回是一个字符串,我想得到我的绑定对象'CustomerViewModel',当我传入我的对象时,它返回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());
        }

If the object is embedded in the query string, MVC will always see it as a string. 如果对象嵌入在查询字符串中,MVC将始终将其视为字符串。

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. 我一直在努力做类似的事情,我不能做Ajax Get或Post,你可以将内容类型设置为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. 很想听到一个可以表现出更简洁的方式的人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM