asp.net mvc下拉列表的客户端验证?

时间:2010-10-22 10:27:09

标签: validation list asp.net-mvc-2 drop-down-menu

我只是想知道如何在asp.net mvc 2中为下拉列表启用客户端验证。 方案是下拉列表将包含“选择”项目和其他项目列表..,用户应选择其他项目......当用户未选择其他项目时,应启动验证

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

在我看来

 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 个答案:

答案 0 :(得分:2)

首先,如果需要下拉列表,请将[Required]属性添加到模型属性中。

然后,在视图顶部的某处启用客户端验证:

<% Html.EnableClientValidation() %>

然后只需添加验证消息:

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

(这需要加载MicrosoftMvcValidation.js)