Search code examples
c#asp.net-mvcdata-annotationsclient-side-validation

data val required not generated using Client Side Validation


I am trying to use Client Side Validation in MVC using data annotations. Data val attribute is not generated and client side validation is not working.

My approach is :

  public partial class User : BaseEntity
    {
        public User()
        {
            this.UserRoles = new List<UserRole>();
        }

        public int UserId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
}

I am using above class as partial class extension:

 [MetadataType(typeof(UserMetaData))]
    public partial class User
    { }

    public class UserMetaData
    {
        [Required]
        public string FirstName { get; set; }
        [Required]
        public string LastName { get; set; }
}

Including View :

@using (Html.BeginForm("Add", "user", FormMethod.Post, new { @class = "form-horizontal"}))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
    @Html.Partial("_UserDetails", Model)

    <div class="col-md-12 col-sm-12 col-xs-12">
        <div class="form-group">
            <div class="col-md-12 col-sm-12 col-xs-12 pull-left">
                <input type="submit" class="btn btn-primary btn_box" value="Add" id="formSubmit" />
            </div>
        </div>
    </div>
}

_UserDetails Partial View :

<div class="form-group">
                            <div class="col-md-4 col-sm-12 col-xs-12">@Html.Label("First Name :", new { @class = "col-sm-12 control-label text-label" })</div>
                            <div class="col-md-8 col-sm-12 col-xs-12">@Html.TextBoxFor(m => m.User.FirstName, new { @class = "form-control input-fild", @id = "firstname" })</div>
                        </div>
                        <div class="form-group">
                            <div class="col-md-4 col-sm-12 col-xs-12">@Html.Label("Last Name :", new { @class = "col-sm-12 control-label text-label" })</div>
                            <div class="col-md-8 col-sm-12 col-xs-12">@Html.TextBoxFor(m => m.User.LastName, new { @class = "form-control input-fild", @id = "lastname" })</div>
                        </div>

When i run the application and see view source "data val" attribute is not generated on the control as it use to generate in normal [Required] attribute.

Am i missing anything ? Thanks.


Solution

  • Can you have a look at the solutions provided for this question. MVC 4 client side validation not working

    Also another one is described in this blog