2014-07-04 24 views
0

我們有以下模型:EditorForModel不ICollection的MVC工作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輸入字段使用名稱「[0] .ConditionValue」而不是「Child_SampleConditions [0] .ConditionValue」進行呈現。這就是爲什麼當我發佈這個表單時,Child_SampleConditions不會自動綁定到模型對象中進入post方法。

有人可能會建議如何正確呈現ICollection輸入字段名稱,以便它們可以自動獲取模型綁定。

注意:請排除自定義模型聯編程序選項。

編輯:我在這裏提供一些更多的信息。 在ManyToOneFieldFor mehtod,使用下面的輔助檢索的名稱:

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

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

請指教..

謝謝。

回答

0

相反的:

O => sampleConditions[0].ConditionValue 

寫:

O => O.Child_SampleConditions[0].ConditionValue 

編輯:

IListICollection不能被索引創建一個視圖模型:

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

+0

沒有不工作。它給出編譯時錯誤:錯誤無法對['System.Collections.Generic.ICollection '表達式應用索引編制' – mmssaann

+0

'您無法索引''ICollection''使用' 'IList''通過創建視圖模型 –

+0

我不認爲我可以改變模型。他們是由建築師設計的。將ICollection更改爲IList會有什麼後果? – mmssaann