【问题标题】:List property doesn't bind on post in controller列表属性不绑定在控制器中的帖子上
【发布时间】:2012-08-30 05:53:27
【问题描述】:

我知道这个问题已经被问了无数次,但请原谅我,因为我现在已经浪费了很多小时,所以终于发布了。 所以总结一下,我有一个视图模型,它有一些复杂的类型属性和一个复杂的类型列表属性。

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

请指点我正确的方向。

谢谢

比拉尔

【问题讨论】:

    标签: asp.net asp.net-mvc-4 viewmodel


    【解决方案1】:

    【讨论】:

      【解决方案2】:

      修改编辑器模板以获取一个列表并在其中执行循环逻辑

      @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%,但你明白了

      【讨论】:

      • 感谢 Daniel 尝试了此操作,但在发布后列表属性绑定为 null。 :(
      【解决方案3】:

      看起来您正试图将您的视图声明为绑定到属性而不是类型。这是不可能的。您必须将模型声明为 Web 项目引用的有效类型,模板才能正常工作。

      Gains 属性的类型为List&lt;Gain>. Since yourGainsview has aGainstype declared, yourUIHintAttribute` 无效。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-02-20
        • 1970-01-01
        • 2014-07-05
        • 2011-08-18
        • 1970-01-01
        • 2014-10-30
        相关资源
        最近更新 更多