我想验证viewmodel的列表,但它没有按预期工作,但它仅适用于viewmodel。这是我的代码 1)HomeController.cs
/((http|https|ftp)\:\/\/[a-zA-Z0-9\-\.]+(:[a-zA-Z0-9]*)?\/?([a-zA-Z0-9\-\._\?\,\/\\\+&%\$#\=~;\{\}])*)|((www)\.+(:[a-zA-Z0-9]*)?\/?([a-zA-Z0-9\-\._\?\,\/\\\+&%\$#\=~;\{\}])*)/gi
2)AddUserPartialView
public PartialViewResult AddUserPartialView()
{
ModelState.AddModelError("AddUserViewModel", "Some Error.");
var UserVMs = new List<AddUserViewModel>() {
new AddUserViewModel{ Name="Name1", Email="Email1@gmail.com"},
new AddUserViewModel{ Name="Name2", Email="Email2@gmail.com"},
new AddUserViewModel{ Name="Name3", Email="Email3@gmail.com"}
};
return PartialView("AddUserPartialView", UserVMs);
}
// GET: /Home/AddUserInfo
[HttpPost]
public JsonResult AddUserInfo(AddUserViewModel model)
{
bool isSuccess = false;
if (ModelState.IsValid)
{
isSuccess = true;
}
return Json(new { success = isSuccess, model = model }, JsonRequestBehavior.AllowGet);
}
3)js文件 $('#AddUserForm')。load('@ Url.Action(“AddUserPartialView”,“Home”)',function(){
var $ form = $('#myForm'); $ .validator.unobtrusive.parse($形式);
$ form.submit(function(){
@model IEnumerable<MvcApplication1.Models.AddUserViewModel>
<form id="myForm" method="post">
@foreach (var user in Model)
{
<div class="form-group">
@Html.LabelFor(m => user.Name)
@Html.TextBoxFor(m => user.Name)
@Html.ValidationMessageFor(m => user.Name)
</div>
<div class="form-group">
@Html.LabelFor(m => user.Email)
@Html.TextBoxFor(m => user.Email)
@Html.ValidationMessageFor(m => user.Email)
</div>
}
</form>
});
4)ViewModel
if ($form.valid()) {
$.ajax({
url: "/Home/AddUserInfo",
async: true,
type: 'POST',
data: $(this).serialize(),
beforeSend: function (xhr, opts) {
},
complete: function () {
},
success: function (data) {
console.log(data);
$("#AddUserForm").dialog("close");
},
error: function (data) {
alert("some rutime error");
}
});
}
return false;
5) Result
问题是,如果我将第一个文本框名称保留为空并填充其余文本框,则会向所有文本框显示验证错误消息。
由于
public class AddUserViewModel
{
[Required(ErrorMessage = "Please enter name !!!")]
public string Name { get; set; }
[Required(ErrorMessage = "Please enter email address !!!")]
[EmailAddress(ErrorMessage = "Please enter valid email address !!!")]
public string Email { get; set; }
}