我的模特是: -
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总是成真。
答案 0 :(得分:0)
您可以使用必需的属性来验证您的模型,例如[Display(Name = "Id")]
,以便为模型中的所有属性显示Id
答案 1 :(得分:0)
制造商可以在模型中拥有自己的类:
public class Instrument
{
[Display(Name = "Id")]
public string Id { get; set; }
[Display(Name = "Instrument Id")]
public String InstrumentId { get; set; }
public List<Manufacturer> Manufacturer { get; set; }
}
public class Manufacturer
{
[Display(Name = "Manufacturer")]
[Required(AllowEmptyStrings=false)]
public string Name
{
get;
set;
}
}
在视图中:
@Html.EditorFor(m => m.Manufacturer[0].Name, new { htmlAttributes = new { @class = "form-control" } })