0

我正在尝试将 IList 绑定到 Html.CheckBoxFor。

当我第一次尝试和调查时,我发现 KeyValuePair 因为它的私有性质而无法完成这项工作,所以我做了一个 MyKeyValuePair。所以现在在我的模型中我有:

public GameCreation()
    {
        Orientation = new List<MyKeyValuePair>();
        foreach (var v in Enum.GetNames(typeof(DeveloperPortalMVCApp.Models.Orientation)))
        {
            Orientation.Add(new MyKeyValuePair { Name = v });
        }
    }

    public MyKeyValuePair MyProperty { get; set; }
    public ObservableCollection<MyKeyValuePair> Orientation { get; set; }

我的看法是:

@Html.CheckBoxFor(model => model.MyProperty.Value)
                    @foreach (var f in Model.Orientation)
                    {
                        @Html.CheckBoxFor(model => f.Value)
                    }

问题是 IList 中的那些 MyKeyValuePair 不会更新它们的值,但 MyProperty 会。我错过了什么?

4

1 回答 1

1

利用

@Html.CheckBoxFor(model => model.MyProperty.Value)
@for (var i=0; i < Model.Orientation.Count; i++)
{
    @Html.CheckBoxFor(model => Model.Orientation[i].Value)
}

特别注意索引器,如果你不索引复选框,那么你最终会得到一堆名称和/或 ID 冲突的复选框。模型绑定器可能会尝试将其绑定为单个项目,而不是列表。

如果你使用上面的代码示例,你会得到类似这样的东西:

<input type="checkbox" name="Orientation[0].Value" />
<input type="checkbox" name="Orientation[1].Value" />
<input type="checkbox" name="Orientation[2].Value" />

其中,模型绑定器可以解释为列表。如果你不使用 CheckBoxFor 中的索引器,那么你会得到类似这样的东西:

<input type="checkbox" name="Orientation.Value" />
<input type="checkbox" name="Orientation.Value" />
<input type="checkbox" name="Orientation.Value" />

并且模型绑定器将无法从中列出。

于 2014-06-10T15:54:20.177 回答