使用asp-for绑定可变数量的标签

问题描述 投票:0回答:1

我有一个视图,用户可以触发一个动作,在页面中插入input标签:

enter image description here

“添加更多”按钮与jquery点击事件相关联。

HTML:

<div id="details">
   <label>More details</label>
   <input placeholder="Foo" asp-for="">
   <input placeholder="Bar" asp-for="">
</div>
<button id="add-details" type="button">Add more</button>

JS:

$("#add-details").click(function(){
  $("#details").append(`<input placeholder="Foo" asp-for="">
      <input placeholder="Bar" asp-for="">`)
});

现在,我想将<input>标签绑定到C#模型,以便在Controller中检索它们的值。但是可能有任何数量的这些标签。

检索它们最方便的方法是作为Dictionary<T>,但我不知道在asp-for属性中放入什么。

那我的Model怎么样?我应该在asp-for属性中添加什么?

c# html asp.net asp.net-mvc asp.net-core-2.0
1个回答
1
投票

虽然this answer不是关于TagHelpers(您正在使用),但请阅读它以了解您需要做什么以及为什么做的背景。

在您的情况下,您将需要添加输入标记,以便它们的名称与索引一样是数组。例如,下面:

<input placeholder="Foo" asp-for="[0].Foo">
<input placeholder="Foo" asp-for="[1].Foo"> 

将映射到一个集合,第一个项目(索引0)将是asp-for="[0].Foo"的输入标记的内容,第二个项目将是asp-for="[1].Foo"的输入标记的内容。

你的控制器动作方法应该接受一个集合。例如,如果您要添加学生,则操作方法可能如下所示:

[HttpPost]
public ActionResult Index(List<Student> students) { ... }

最后,请参阅docs的表达式名称和集合以获取更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.