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

1 Answer 1

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
 }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.