MVC DropDownListFor和StringLength属性不能很好地配合使用 [英] MVC DropDownListFor and StringLength Attribute Not Playing Well together

查看:108
本文介绍了MVC DropDownListFor和StringLength属性不能很好地配合使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在具有字符串值的下拉列表中,我的字符串长度验证始终失败.

My stringlength validation always fails on dropdownlists with a string value.

这是我的模特:

[Required(ErrorMessage = "Required")]
[StringLength(2, MinimumLength = 2)]
[Display(Name = "Home Address State")]
public string HomeAddressState { get; set; }

这是我的观点:

@Html.DropDownListFor(model => model.HomeAddressState, new SelectList(ViewBag.States, "Value", "Text"), string.Empty)
@Html.ValidationMessageFor(model => model.HomeAddressState)

这是html输出:

<select data-val="true" data-val-length="The field Home Address State must be a string with a minimum length of 2 and a maximum length of 2." data-val-length-max="2" data-val-length-min="2" data-val-required="Required" id="HomeAddressState" name="HomeAddressState"><option value=""></option>
<option value="CA">California</option>
<option value="IL">Illinois</option>
<option value="IN">Indiana</option>
<option value="OH">Ohio</option>
</select>

无论选择什么选项,StringLength验证都会在客户端失败.我在做什么错?

No matter what option is selected, the StringLength validation fails client-side. What am I doing incorrectly?

推荐答案

以下是相关的jquery验证代码.如您所见,它似乎将长度验证应用于所选选项的数量,而不是选项的长度.似乎仅适用于多选列表框.老实说,有点奇怪.

Here's the relevant jquery-validation code. As you can see, it looks like it applies the length validation to the number of options selected, not the length of the option. Seems to only apply to multi-select listboxes. Kind of odd, to be honest.

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

您可以做的是自己重写getLength函数,直接返回value.length.

What you can do is override the getLength function yourself to just return value.length directly.

$.validator.prototype.getLength = function (value, element) {
    return value.length;
}

这篇关于MVC DropDownListFor和StringLength属性不能很好地配合使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆