问题
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