【发布时间】:2015-09-30 07:20:46
【问题描述】:
我的模型是:-
public class instrument
{
[Display(Name = "Id")]
public string Id { get; set; }
[Display(Name = "Instrument Id")]
public String InstrumentId
{
get;
set;
}
[Display(Name = "Manufacturer"),Required(AllowEmptyStrings=false)]
public List<string> manufacturer
{
get;
set;
}
.....
.....
}
我的观点有这些
<div class="form-group">
@Html.LabelFor(model => model.manufacturer[0], htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.manufacturer[0], new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.manufacturer[0], "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.manufacturer[1], htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.manufacturer[1], new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.manufacturer[1], "", new { @class = "text-danger" })
</div>
</div>
当我向控制器提交表单时(没有在这两个文本框中输入任何值),列表制造商包含两个空字符串。我想验证这些。因为 Model.IsValid 总是为真,因为制造商有两个空字符串。
【问题讨论】:
-
您想要的实际验证是什么(
[Required]不适用于集合) - 您是否要确保集合中的每个项目都不是 null/空字符串? -
是的。我想这样做。
-
那么属性
manufacturer需要是List`,其中 Manufacturer是一个包含属性(例如)string Name的类,该属性用[Required]属性修饰。但是您不应该以这种方式生成您的视图。相反,使用for循环 -
好的。但我认为这些是制造商名称的简单字符串。因为我将它们保存在 documentDB 中。谢谢。
-
[Required]验证您应用它的属性不是null。由于您的List<string>永远不会是null,所以它总是通过验证
标签: asp.net-mvc c#-4.0 asp.net-mvc-5 data-annotations asp.net-mvc-5.1