EditorForModel不使用ICollection MVC 4

时间:2014-07-04 05:01:15

标签: asp.net-mvc-4 entity-framework-4

我们有以下型号:

public class Sample
{
    public int SampleId { get; set; }
    public int ToTestId { get; set; }
    public int Name { get; set; }
    public virtual ICollection<SampleCondition> Child_SampleConditions { get; set; }
}

我在我的视图中渲染它们如下:

@model Sample
@{
    string cntlrName = ViewContext.RouteData.GetRequiredString("controller");
    List<SampleCondition> sampleConditions  = Model.Child_SampleConditions.ToList();
    if (d2l.NullOrEmpty(sampleConditions))
    {
        Model.Child_SampleConditions .Add(new SampleCondition());
    }
    List<SampleCondition> sampleConditions = Model.Child_SampleConditions as                List<SampleCondition>;
    }
    @Html.ValidationSummary(true)

    @Html.d2_HiddenFor(O => O.SampleId)

    <div class="@BOOTSTRAP.ROW">
        @Html.ManyToOneFieldFor(Model, O => O.ToTestId, allowed: CrudFlag.Editable)
        @Html.FieldFor(O => O.Name, allowed: CrudFlag.Editable)
        @Html.FieldFor(O => sampleConditions[0].ConditionValue, allowed:CrudFlag.Editable)
    </div>

请查看div中的第三个文件,sampleConditions [0] .ConditionValue。此控件的html输入字段使用名称&#34; [0] .ConditionValue&#34;进行渲染。而不是&#34; Child_SampleConditions [0] .ConditionValue&#34;。这就是为什么当我发布这个表单时,Child_SampleConditions不会自动绑定到模型对象到post方法。

有人可以建议如何正确渲染ICollection输入字段名称,以便它们可以自动获取模型绑定。

注意:请排除自定义模型绑定选项。

编辑:我在这里提供更多信息。 在ManyToOneFieldFor mehtod中,使用下面的帮助程序检索名称:

 string fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);

它只返回[0] .ConditionValue但不返回Child_SampleConditions [0] .ConditionValue。

请告知..

感谢。

1 个答案:

答案 0 :(得分:0)

而不是:

O => sampleConditions[0].ConditionValue

写:

O => O.Child_SampleConditions[0].ConditionValue

修改

创建一个IList的ViewModel,因为ICollection无法编入索引:

public class SampleVM
{
    public int SampleId { get; set; }
    public int ToTestId { get; set; }
    public int Name { get; set; }
    public virtual IList<SampleCondition> Child_SampleConditions { get; set; }
}

参考链接:Cannot apply indexing with [] to an expression of type ICollection