如何将jQuery validate插件与强类型枚举一起使用? [英] How to use the jQuery validate plugin with strongly typed enumerations?

查看:83
本文介绍了如何将jQuery validate插件与强类型枚举一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是强类型视图,该视图列出了对象的枚举,如下所示:

I am using a strongly typed view that lists an enumeration of objects, something like this:

@model IEnumerable<Foo>

<table>
    <tbody>
        @Html.EditorForModel()
    </tbody>
</table>

让我们说Foo有一个简单的数字属性,我想在客户端进行验证:

Let's say Foo has a simple numeric property that I want to validate on the client side:

public class Foo
{
    [Required]
    public int Bar { get; set; }
}

现在,该对象的编辑器模板如下所示:

Now the editor template for this object looks like this:

@model Foo

<tr>
    <td>@Html.TextBoxFor(m => m.Bar)</td>
</tr>

这正常工作,除了默认模型联编程序会生成类似[0].Bar的名称.但是,[]对于jQuery validate插件是无效字符,因此,每当它尝试验证我的输入时,我总是会收到以下错误:

This works fine, except that the default model binder generates names like [0].Bar. However, [ and ] are invalid characters for the jQuery validate plugin and thus I am always receiving the following error whenever it tries to validate my input:

语法错误,无法识别的表达式:label [for ='[0] .Bar'],label [for ='[0] .Bar'] *,#[0] .Bar

Syntax error, unrecognized expression: label[for='[0].Bar'], label[for='[0].Bar'] *, #[0].Bar

在保持我的视图与模型绑定的同时,有什么方法可以使插件正常工作?

Is there any way to get the plugin to work while keeping my view bound to the model?

更新:我正在使用jQuery Validate和Microsoft的Unobstrusive Validation库(是的,默认的ASP.NET MVC设置),因此我根本不会直接编写任何验证代码,即使它是兴趣!

Update: I am using jQuery Validate and Microsoft's Unobstrusive Validation library (yep, the default ASP.NET MVC setup), so I am not directly writing any validation code at all, just if it's of interest!

推荐答案

[和]字符对于jQuery validate插件不是严格无效的.这只是草率的编码,没有考虑在名称/标识中包含这些字符的可能性.

The [ and ] characters aren't strictly invalid for jQuery validate plugin. It's just a sloppy coding which doesn't account for possibility to have those chars in name/id.

甚至还有GitHub问题处理ASP.NET MVC输入数组异常为此.

There is even a GitHub issue Handling ASP.NET MVC Input Arrays Exception for this.

我所做的是我从问题中取出了代码(它本身就有一个小问题),并将此hack添加到了我的JavaScript初始化代码中:

What I did is I took the code from issue (it has a small problem on it's own) and added this hack on my JavaScript initialization code:

$.validator.prototype.idOrName = function(element) {
    return this.groups[element.name]
        || (this.checkable(element)
            ? element.name
            : element.id || element.name)
        .replace("[", "\\[")
        .replace("]", "\\]");
}

那可能不是最美或最好的解决方案,但对我有用.至少直到它在jQuery中修复为止.

That might not be pretiest or best solution but it works for me. At least till it's fixed in jQuery.

无需使用此功能,因为它可以与1.13.1一起使用(有关讨论,请参见上面的问题).请注意,尽管我尚未检查自己,但ASP.NET MVC仍可能与1.13.0捆绑在一起

这篇关于如何将jQuery validate插件与强类型枚举一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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