在Razor视图中按要求制作字段 [英] Making a field as required in Razor view
问题描述
我想在剃刀视图中根据需要创建一个文本框字段.我不能使用验证属性[Required]
,因为字段名称是动态生成的.我检查了此答案,它设置了data-val-required
字段使用javascript到true
.还有其他方法可以执行此操作,因为在运行项目之前我不会知道字段ID?
I want to make a text box field as required in the razor view. I can't use validation attribute [Required]
because the field names are generated dynamically. I checked this answer which sets the data-val-required
field to true
using javascript. Is there any other way to do this as I wont be knowing the field id before running the project?
我尝试了下面的代码,并且现在可以正常工作,除了验证消息未显示在表单提交上.
I tried the code below and it works now, except that the validation message is not displayed on form submission.
@for (int i = 0; i < Model.Controls.Length; i++)
{
@Html.TextBoxFor(x => x.Controls[i].Value, new { id = obj.VitalName, data_val_required = "true" })
@Html.ValidationMessageFor(x => x.Controls[i].Value, "Please fill in the details.")
</td>
</tr>
}
推荐答案
在html属性中使用@required = true
而不是data_val_required = "true"
Use @required = true
inside the html attributes instead of data_val_required = "true"
@Html.TextBoxFor(x => x.Controls[i].Value, new { id = obj.VitalName, @required = true })
这篇关于在Razor视图中按要求制作字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!