Htm.Dropdown为验证问题

时间:2013-04-19 16:27:45

标签: asp.net-mvc validation asp.net-mvc-4 jquery-validate

我正在研究一个MVC4项目,我有一些奇怪的行为,jQuery验证检查下拉列表中的文本而不是值:

    // field in model
    [Required]
    [DataType(DataType.Text)]
    [StringLength(2, ErrorMessage = "The {0} must be {2} characters long.", MinimumLength = 2)]
    [Display(Name = "State")]
    public string StateCode { get; set; }

    // source of states  -> List.States
    Dictionary<string, string> states = new Dictionary<string, string>();
      states.Add("AK", "Alaska");
      states.Add("AZ", "Arizona");
      // etc.
      states.Add("WI", "Wisconsin");
      states.Add("WY", "Wyoming");
    }

    // in the controller
    ViewBag.States = new SelectList(Lists.States(), "Key", "Value", Lists.States["AK"]);

    <!-- in the view -->
    <li>
      @Html.LabelFor(m => m.StateCode)
      @Html.DropDownListFor(m => m.StateCode, (SelectList)ViewBag.States, "Alaska")
    </li>

这是我收到的错误消息: •州的长度必须为2个字符。

1 个答案:

答案 0 :(得分:0)

我认为这是因为jquery正在检查所选项目的数量。

maxlength: function(value, element, param) {
    return this.optional(element) || this.getLength($.trim(value), element) <= param;
}

getLength: function(value, element) {
    switch( element.nodeName.toLowerCase() ) {
        case 'select':
            return $("option:selected", element).length;
        case 'input':
            if( this.checkable( element) )
                return this.findByName(element.name).filter(':checked').length;
    }
    return value.length;
}