asp.net - 如何在 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; }
}
我有一个表格,其中有一个字段:
- 标题
- 多个参与者
<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-for="@Model.Participants[0].Name"
,它会工作。同样对于动态绑定列表,您可以尝试循环,Model.Participants
如下所示。
<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>
推荐阅读
- append - Dataweave 在变换中追加
- tensorflow - 没有为任何变量/自定义损失提供梯度
- php - 共享 cPanel 托管包不提供可用于 WordPress 网站的临时 URL
- matlab - 在 Matlab R2020a 中打开脚本时出错
- apache-spark - Spark randomSplit 训练和测试数据行数总是给出不同的结果
- c# - 当找不到我在顶部指定的网站 url 时,我如何创建 else 或 if 语句在 usrNameLabel 中创建文本
- http - 非英语语言的 HTTP 自定义 Header 键名
- mysql - 如何更改 mysql 表中的 ID-s 顺序(按值排序记录)
- javascript - 用户拒绝后使用 JS 在 IE 11 中调用剪贴板访问提示
- typescript - 如何使用 VSCode api 打开自定义编辑器