首页 > 解决方案 > 如何在 ASP.Net 中绑定包含列表的复杂类型?

问题描述

所以,我有一个这样的模型:

public class EventViewModel
{
    public string Title { get; set; }
    public List<EventParticipant> Participants { get; set; }
}

public class EventParticipant
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public string Strength { get; set; }
    public string Losses { get; set; }

}

我有一个表格,其中有一个字段:

  1. 标题
  2. 多个参与者
    <form asp-controller="Event" asp-action="Create" method="post">  

        <input asp-for="Title" class="form-controls/>
                                
        <input asp-for="Participants[0].Name" class="form-controls/>                                
        <input asp-for="Participants[0].Strength" class="form-controls/>      
        <input asp-for="Participants[0].Losses" class="form-controls/>    
     
        <input asp-for="Participants[1].Name" class="form-controls/>                                
        <input asp-for="Participants[1].Strength" class="form-controls/>      
        <input asp-for="Participants[1].Losses" class="form-controls/> 
         
        <input type="submit" class="form-controls/>     
    </form>

当我使用上面的代码进入页面时,我收到以下错误:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

突出显示第一个“参与者”输入。

我怎样才能做到这一点,以便在发布后,我可以访问参与者列表,如下所示:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(EventViewModel model)
    {
        foreach (var participant in model.Participants)
        {
            Debug.WriteLine("Name: " + participant.Name);
        }
        return RedirectToAction("Create");
    }

标签: asp.netasp.net-core

解决方案


使用asp-for="@Model.Participants[0].Name",它会工作。同样对于动态绑定列表,您可以尝试循环,Model.Participants如下所示。

有关更多详细信息,请参阅https://docs.microsoft.com/en-us/aspnet/core/mvc/views/working-with-forms?view=aspnetcore-3.1#expression-names-and-collections

<form asp-controller="Event" asp-action="Create" method="post">  

    <input asp-for="Title" class="form-controls/>
                        
    @for (int i = 0; i < Model.Participants.Count; i++)
    {       
        <input asp-for="@Model.Participants[i].Name" class="form-controls/>                                
        <input asp-for="@Model.Participants[i].Strength" class="form-controls/>      
        <input asp-for="@Model.Participants[i].Losses" class="form-controls/>    
    }
     
    <input type="submit" class="form-controls/>     
</form>

推荐阅读