Bind variable number of tags with asp-for

泄露秘密 提交于 2019-12-08 12:46:15

问题


I have a view where an user can trigger an action that will insert input tags in the page:

The 'Add more' button is tied to a jquery click event.

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="">`)
});

Now, I want to bind the <input> tags to a C# Model, in order to retrieve their values in a Controller. But there could be any amount of these tags.

The most convenient way to retrieve them would be as a Dictionary<T>, but I don't know what to put in the asp-for attributes.

So how should my Model look like? What should I put in my asp-for attributes?


回答1:


Although this answer is not about TagHelpers (which you are using), please read it to give you a background of what you need to do and why.

In your case you will want to add input tags so their names are array-like with indices. For example, below:

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

will map to a collection and the first item's (index 0) will be the contents of the input tag with asp-for="[0].Foo" and the second item's will be the contents of the input tag with asp-for="[1].Foo".

You controller action method should accept a collection. For example, if you were adding students, then the action method may look like this:

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

Finally, please refer the Expression names and Collections of the docs for more info.



来源:https://stackoverflow.com/questions/48477332/bind-variable-number-of-tags-with-asp-for

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!