2

i just wanted to know how to enable client side validations for dropdowns in asp.net mvc 2. The scenario would be that the dropdown will contain a "Select" item and the list of other items..,The user should select other items... the validation should fire when the user does not select the other items

public class FacilityBulletinModel
    {
        [DisplayName("Select a Facility")]
        public List<SelectListItem> ListFacility { get; set; }

        [DisplayName("Facility Bulletin")]
        [Required(ErrorMessage = "Please create a Bulletin")]
        public string FacilityBulletin { get; set; }

        [DisplayName("Active")]
        public bool Active { get; set; }

       [HiddenInput(DisplayValue = false)]
        public int SiteId { get;set;}
    }

in my view

 Select Facility <span class="err">*</span><br />
    <%=Html.DropDownListFor(model => model.ListFacility, null, new {onChange="updateSiteId()" })%>
   <span class="err"> <%= Html.ValidationMessageFor(model => model.ListFacility) %></span>

1 Answer 1

2

First, if a dropdown is required, add the [Required] attribute to your model property.

Then, enable client side validation somewhere at the top of your view:

<% Html.EnableClientValidation() %>

Then just add a validation message:

<div class="inputField">
    <%= Html.LabelFor(model => model.property)%>
    <%= Html.DropDownListFor(model => model.property, (SelectList)ViewData["myselelectlist"])%>
    <%= Html.ValidationMessageFor(model => model.property)%>
</div>

(this requries MicrosoftMvcValidation.js to be loaded)

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.