我有以下电话:
@Html.TextBoxFor(m => m.SelectedName)
@Html.TextBoxFor(m => m.Selections[0].Name)
在这两种情况下,我分别用以下注释标记SelectedName
andName
[Required(ErrorMessage = "Please provide required value")]
但是 SelectedName 打印正确的不显眼的 html 属性:
<input id="SelectedName" name="SelectedName" data-val="true" data-val-required="Please provide required value">
其中 m.Selections[0].Name 显示如下:
<input id="Selections_0__Name" name="Selections[0].Name" value="" type="text">
是什么赋予了?我不敢相信这种情况在 MVC4 中被忽略了,这似乎是一个相当常见的用例。我将如何验证作为数组或包含数组的视图模型?
=====================为清晰起见编辑为 ViewModel 添加代码=====================
public class ContainerVM
{
[Required]
public string SelectedName {get;set;}
public MemberVM[] Selections {get;set;}
}
public class MemberVM
{
[Required]
public string Name { get;set; }
}
=====================表格====================
@using MyProject.Models;
@model ContainerVM
@{
ViewContext.FormContext = new FormContext(); //This is just a hack because the parent isn't defined yet.
}
@Html.TextBoxFor(m => m.SelectedCptGroupId)
@Html.TextBoxFor(m => m.CptGroupSelections[0].Name)