0

I want to validate the list of viewmodel but it is not working as expected however it is work for only viewmodel. Here are the my codes 1) HomeController.cs

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);
        }

2) AddUserPartialView

@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>

3) js file $('#AddUserForm').load('@Url.Action("AddUserPartialView", "Home")', function () {

var $form = $('#myForm'); $.validator.unobtrusive.parse($form);

$form.submit(function () {

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;

});

4) ViewModel

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; }
    }

5) Result

Problem is, if i kept 1st textbox Name empty and fill the rest of textboxes, it is showing the validation error message to all the textbox.

Thanks

enter code here
sajan k
  • 11
  • 5
  • You cannot use a `foreach` loop to generate form controls for a collection. It needs to be a `for` loop (or `EditorTemplate`) as per the dupe. –  Jun 13 '18 at 23:35
  • @StephenMuecke - I've tried for loop but syntax problem, Can you please write down for loop condition for this scenario? thanks – sajan k Jun 14 '18 at 13:16
  • What syntax problem? - read the dupe carefully and follow it –  Jun 15 '18 at 02:32
  • I fixed it, I have changed IEnumerable Model to List and working as expected. Thanks – sajan k Jun 15 '18 at 07:32

0 Answers0