1

I am trying to validate the dropdown list in MVC 5 .But it's not working. Below is my View:

<div class="form-group">
    @Html.LabelFor(model => model.Gender, htmlAttributes: new { @class = "control-label col-md-4" })
    <div class="col-md-4">
        @Html.DropDownList("Gender", new List<SelectListItem>
        {
            new SelectListItem {Text ="Male", Value="Male" },
            new SelectListItem {Text ="Female", Value="Female" }
        },
        "Select Gender")

In my Model, i have specified this field as required. But it still not working. Below is my model:

[Required(ErrorMessage = "Please select Gender.")]
public string Gender { get; set; }
Irshu
  • 8,248
  • 8
  • 53
  • 65
Abrar
  • 41
  • 1
  • 5
  • possible duplicate of [Required Attribute not working in asp net mvc](http://stackoverflow.com/questions/19734608/required-attribute-not-working-in-asp-net-mvc) – Polynomial Proton Apr 23 '16 at 20:21

1 Answers1

0

If you need the client to validate before making the post, first you need to make sure UnobtrusiveJavascript is enabled in your Web.Config. Check if UnobtrusiveJavaScriptEnabled is set to true.

If you are making an ajax request, you need to validate the form explicity like:

 var $form = ('#myForm');
 $.validator.unobtrusive.parse($form);
 if ($form.valid())
 {
    // continue with the POST
 }
Irshu
  • 8,248
  • 8
  • 53
  • 65