【问题标题】:Populate List<Objects> From Mvc 3 view从 Mvc 3 视图填充 List<Objects>
【发布时间】:2012-03-21 07:23:31
【问题描述】:

我有一个基于 Nominees 的 Viewmodel。我可以有多个视图模型的提名者。

我想从视图中填充 Ilist。这是我的视图模型

public class DebitViewModel:IValidatableObject
{
    public string AgentName { get; set; }
    public Debit Debit { get; set; }

    public Policy Policy { get; set; }
    public PolicyType PolicyType { get; set; }
    public Customer Customer { get; set; }     

    public IList<PolicyType> PolicyTypes { get; set; }
    public List<Nominee> Nominees { get; set; }
    public Dictionary<int,string> OccupationTypes { get; set; }        
}

我想在按下 submit 时自动填充所有 Nominess。那么我应该如何通过视图创建并使其自动填充列表?而不是单独的对象?

【问题讨论】:

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


    【解决方案1】:

    您可以使用编辑器模板:

    @model DebitViewModel
    @using (Html.BeginForm())
    {
        ... some input fields for the other properties that we are not interested in
    
        @Html.EditorFor(x => x.Nominees)
    
        <button type="submit">OK</button>
    }
    

    然后您为 Nominee 模型 (~/Views/Shared/EditorTemplates/Nominee.cshtml) 定义一个自定义编辑器模板,该模板将为 Nominees 集合的每个元素自动呈现:

    @model Nominee
    
    <div>
        @Html.EditorFor(x => x.FirstName)
        @Html.EditorFor(x => x.LastName)
        ...
    </div>
    

    【讨论】:

    • 它没有工作,因为它是一个列表。提名编辑器模板无法显示提名名单:(我试过它没有显示模板字段。好像我对单个提名人做同样的事情。它显示所有模板字段:)
    • @Joy,您的自定义编辑器模板的命名可能有误。名称和位置非常重要。它必须是~/Views/Shared/EditorTemplates/Nominee.cshtml,并且会自动为集合的每个元素呈现模板。
    • 但我看到只有一个被提名人​​工作正常。我的意思是说@Html.EditorFor(x =&gt; x.Nominee) 工作正常。如果我的编辑器模板名称和位置是错误的,那么即使它也不会呈现单个 Nominee :) 但它可以正常工作。唯一的问题是public List&lt;Nominee&gt; Nominees :)
    • @Joy,您应该使用@Html.EditorFor(x =&gt; x.Nominees) 而不是@Html.EditorFor(x =&gt; x.Nominee)。如果您的模板名称和位置错误,它将呈现被提名者。只是它将使用默认模板,而不是您的自定义模板。
    【解决方案2】:

    比如说Nominee看起来像

    public class Nominee{
     public int Id{get;set;}
     public string Name{get;set;}
     public int Age {get;set;}
    }
    

    视图看起来像

    @for (int i = 0; i < Model.Nominees.Count(); i++)
    { 
    <tr>                                                           
      <td>@Html.TextBoxFor(m => m.Nominees[i].Name)</td>
      <td>@Html.TextBoxFor(m => m.Nominees[i].Age)</td>
    </tr>
    }
    

    阅读更多关于model binding to a list

    【讨论】:

    • 是的,我知道,但我需要在 HttpPost 事件中填充列表。它会自动填充 Nominess 列表吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-19
    • 1970-01-01
    • 1970-01-01
    • 2014-01-20
    • 1970-01-01
    相关资源
    最近更新 更多