Search code examples
asp.netvalidationmodel-view-controller

ASP.NET MVC: ValidationMessageFor on multiple input field with same model


I encountered some problems using the input field validation generated from forloop statement. The only problem is the validation only works on the first input text with the same model attribute. Here's the sample:

In my model I'm using array property

public class MembershipModel
{
    [Required]
    [Display(Name = "First Name")]
    public string[] Fname { get; set; }
}

and in the view page

@model MainModel
@using (Html.BeginForm("CreateMember", "Membership", FormMethod.Post, new { role = "form", id = "myForm", @class = "form-horizontal", enctype = "multipart/form-data" }))
{
    @for (var i = 1; i <= 2; i++)
    {
         <label>First Name</label>
         <i class="fa fa-asterisk req-ico"></i>
         @Html.TextBoxFor(m => m.MembershipModel.Fname, new { @class = "memb form-control"})
         @Html.ValidationMessageFor(m => m.MembershipModel.Fname, "", new { @class = "text-danger" })
    }

<button type="button" class="btn btn-primary btn-modal" onclick="$('#myForm').submit();"><strong>Continue</strong></button>
}

I'm confused why my validation works only on the first textbox field. Thank you for helping.


Solution

  • Why validation works only on the first textbox field:

    Reason validation works only on the first textbox field

    As you can see from the image, it's bind and validate data only for MembershipModel.Fname.

    Probable Solution:

    You need to Change MembershipModel to List< MembershipModel >:

    public class MainModel
    {
        public List<MembershipModel> MembershipModels { get; set; }
    }
    

    View Page should be like this:

    @model MainModel
    
    @using (Html.BeginForm("Index","Home", FormMethod.Post, new { role = "form", id = "myForm", @class = "form-horizontal", enctype = "multipart/form-data" }))
    {
        @for (var i = 0; i <= 1; i++)
        {
            <label>First Name</label>
            <i class="fa fa-asterisk req-ico"></i>
            @Html.TextBoxFor(m => m.MembershipModels[i].Fname, new { @class = "memb form-control" })
            @Html.ValidationMessageFor(m => m.MembershipModels[i].Fname, "", new { @class = "text-danger" })
        }
    
    <button type="button" class="btn btn-primary btn-modal" onclick="$('#myForm').submit();"><strong>Continue</strong></button>
    }
    
    @section Scripts
    {
        @{await Html.RenderPartialAsync("_ValidationScriptsPartial");
        }
    }