【问题标题】:Binding query string to object in ASP.NET MVC?将查询字符串绑定到 ASP.NET MVC 中的对象?
【发布时间】:2012-10-30 18:10:58
【问题描述】:

我有一个绑定到 IEnumerable 模型的网格控件。如何在我的控制器中保存记录。我使用的网格控件来自 Telerik 'Kendo'。返回的请求是一个字符串,我想获取我的绑定对象'CustomerViewModel',但是当我传入我的对象时它返回 null。我尝试了不同类型的信息,它似乎只适用于我指定我想传递的属性。请在下面找到代码并提供帮助?

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

【问题讨论】:

  • 你能把你的代码贴出来

标签: c# asp.net-mvc asp.net-mvc-3 controller model-binding


【解决方案1】:

如果对象嵌入在查询字符串中,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 Get 或 Post,您可以将内容类型设置为 JSON。在查询字符串中似乎没有办法做到这一点(这确实有意义,因为它只是一个字符串)。

在控制器中对其进行反序列化似乎是唯一的选择。很想听听有人能展示出一种更简洁的方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多