用asp-for绑定可变数量的标签 [英] Bind variable number of tags with asp-for
问题描述
我有一个视图,用户可以触发在页面中插入 input
标签的操作:
'添加更多'按钮绑定到jquery点击事件。
HTML:
< div id =details>
< label>更多详情< / label>
< input placeholder =Fooasp-for =>
< input placeholder =Barasp-for =>
< / div>
< button id =add-detailstype =button>添加更多< /按钮>
JS:
$(#add-details)。click(function(){
$(#details)。append(`< input placeholder =Fooasp-for = >
< input placeholder =Barasp-for =>`)
});
现在,我想绑定< input>
标记到C#模型中,以便在Controller中检索它们的值。但是可以有任何数量的这些标签。
检索它们的最便捷方式是 asp-for
属性中放置什么。
我的模型
看起来应该如何?我应该在 asp-for
属性中放置什么?
这个答案不是关于TagHelpers(你正在使用的),请阅读它给你一个你需要的背景做和为什么。
在你的情况下,你会想添加输入标签,所以他们的名字是像索引一样的数组。例如:
< input placeholder =Fooasp-for =[0] .Foo>
< input placeholder =Fooasp-for =[1] .Foo>
将映射到一个集合,并且第一个项目(索引0)将成为输入标记的内容 asp-for =[0] .Foo
,第二项是 asp-for =[ 1] .Foo
。
您的控制器操作方法应该接受一个集合。例如,如果您添加学生,那么操作方法可能如下所示:
[HttpPost]
public ActionResult索引(列表< Student>学生){...}
最后,请参阅表达式名称和集合 docs 了解更多信息。
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?
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.
这篇关于用asp-for绑定可变数量的标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!