2012-08-30 37 views
1

我知道這個問題已經被問過幾十萬次,但請原諒我,因爲我現在浪費了很多小時,因此最終發佈了它。 所以總結我有一個視圖模型有一些複雜的類型屬性和一個複雜的類型列表屬性。列表屬性不綁定在控制器上的帖子

public class ViewModel 
{ 
    public ViewModel() 
    { 
     Gains = new List<Gain>(); 

    } 
    [UIHint("Common")] 
    public AllRegRecordsLog commonRegisterFields { get; set; } 
    public Potential Potential { get; set; } 
    [UIHint("Gains")] 
    public List<Gain> Gains { get; set; } 

    public void CreateGains(int count = 1) 
    { 

     for (int i = 0; i < count; i++) 
     { 

      Gains.Add(new Gain()); 

     } 


    } 

} 

現在我的看法createOrEdit我把這個財產,

@Html.EditorFor(model => model.Gains) 

我已經把我的具體看法文件夾中的編輯模板

@model Gains 
    table id="gainsTable" class="content-tables"style="width:98%"> 
    <tr id="defaultGainsRow"> 
      <td class="editor-label"> 
       @Html.LabelFor(model => model.VolumeGainLow) 
      </td> 
      <td class="editor-field"> 
       @Html.TextBoxFor(model => model.VolumeGainLow) 
       @Html.ValidationMessageFor(model => model.VolumeGainLow) 
      </td> 

      </tr> 

    <tr> 
    <td colspan="4"> 
     <input id="addGainsButton"type="button" class="t-button" Value="Add Potential Gains"/> 
    </td> 
    </tr> 
    </table> 

但不知何故,我得到的錯誤「傳遞到字典中的模型項目類型爲「System.Collections.Generic.List,但期望收益」

我正在使用asp.Net MVC 4

請指點我正確的方向。

感謝

比拉爾

回答

0

修改editortemplate採取列表,並執行

@model List<Gain> 
@foreach(var gain in Model) 
{ 
    table id="gainsTable" class="content-tables"style="width:98%"> 
    <tr id="defaultGainsRow"> 
      <td class="editor-label"> 
       @Html.LabelFor(gain=> gain.VolumeGainLow) 
      </td> 
      <td class="editor-field"> 
       @Html.TextBoxFor(gain=> gain.VolumeGainLow) 
       @Html.ValidationMessageFor(gain=> gain.VolumeGainLow) 
      </td> 

      </tr> 

    <tr> 
    <td colspan="4"> 
     <input id="addGainsButton"type="button" class="t-button" Value="Add Potential Gains"/> 
    </td> 
    </tr> 
    </table> 
} 

編輯裏面的循環邏輯:我的剃鬚刀也不可能是100%,但你的想法

+0

感謝丹尼爾試過,但隨後後門柱列表屬性綁定爲空。 :( – Bilal

0

它看起來像你試圖聲明你的視圖綁定到屬性而不是類型。這不可能。您必須將模型聲明爲您的Web項目引用的有效類型才能使模板生效。

的類型Gains屬性的是List<Gain>. Since your收益view has a收益type declared, your UIHintAttribute`是無效的。

+0

好吧,我刪除它,但現在什麼都沒有顯示在視圖:( – Bilal