MVC模式不具约束力字典 [英] MVC model not binding to dictionary

查看:94
本文介绍了MVC模式不具约束力字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用ASP.Net MVC4(剃刀)。我有以下的code:

I am using ASP.Net MVC4 (Razor). I have the following code:

词典<字符串,OccasionObject> occasionList =新词典<字符串,OccasionObject>()

关键是的场合类的字符串。该occassion对象有3个属性: isAttending(布尔) ID(INT)名称(字符串)

The key is a string of the category of the occasion. The occassion object has 3 properties: isAttending(bool), ID(int), and Name(string)

在我CSHTML文件,我做到以下几点:

In my cshtml file, I do the following:

@foreach(string s in model.occasionList .Keys)
{
   foreach(var o in model.occasionList .Keys[s])
   {
      @Html.CheckBoxFor(m=>m.occasionList[s].FirstOrDefault(ev=>ev.ID == o.ID).isAttending);
   }
}

此完美结合的负载,检查我在SQL人工检查框。然而,当我张贴这种模式回服务器,该occasionList字典为空。该模型结合很好,因为其他属性我在模型仍返回。

This binds perfectly on the load, checking boxes that I have manually checked in SQL. However, when I POST this model back to the server, the occasionList dictionary is null. The model is binding fine because other properties I have in the model are still returned.

任何想法?

谢谢,
大教堂

Thanks, Dom

推荐答案

模型绑定对待字典作为一个集合,如果你想像字典作为的IEnumerable< KeyValuePair<字符串的IEnumerable< OccasionObject> >方式> 就很容易理解为什么它不绑定

The model binder treats the dictionary as a collection, if you imagine the dictionary as an IEnumerable<KeyValuePair<string, IEnumerable<OccasionObject>>> it is easy to understand why it isn't bound.

什么 @ Html.CheckBoxFor(M = GT; m.occasionList [S] .FirstOrDefault(EV =&GT; ev.ID == o.ID).isAttending); 是发电是:

&LT;输入类型=复选框NAME =occasionList [0] .Value.isAttending../& GT;

所以关键是缺少的。

试试这个:

@Html.Hidden("occasionList.Index", s)
@Html.CheckBoxFor(m=>m.occasionList[s].FirstOrDefault(ev=>ev.ID == o.ID).isAttending);
@Html.HiddenFor(m=>m.occasionList[s].Key)

第一个隐藏的是因为你可能有你自己的指标失灵,的 并明确规定了的.index 是有在这些情况下模型绑定工作的唯一途径。

The first hidden is because you potentially will have your indexes out of order, and explicitly providing an ".Index" is the only way to have the model binder work under those circumstances.

<一个href=\"http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx\"相对=nofollow> 这里 描述模型绑定到集合的其他资源。

Here's another resource that describes model binding to collections.

这篇关于MVC模式不具约束力字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆