views:

16

answers:

1

hi, 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>
A: 

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)

James Connell