带有无效变量名的jQuery验证远程:如何解决? [英] jQuery Validation remote with invalid variable name: How to fix?

查看:134
本文介绍了带有无效变量名的jQuery验证远程:如何解决?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将远程与jQuery验证一起使用.

I'm using remote validation with jQuery Validation.

我试图在MVC中调用服务器端代码,但问题是我的变量在嵌套类中:

I'm trying to call my server side code in MVC but the problem is that my variable is in a nested class:

public class Customer
{
    public State HouseState {get;set;}
}

public class State
{
    public string Name {get;set;}
}

在我的* .cshtml中,我有这个:

In my *.cshtml I have this:

@Html.TextBoxFor(m => m.HouseState.Name, new { placeholder = "State Name"})

我为此添加验证:

    $.validator.addMethod("verify", verify);

    $('#HouseState_Name').rules('add', {
        verify: true,
        remote: '@Url.Content("~/Home/Validate")',
        messages: { verify: "No!" }
    });

在这种情况下,它将生成这样的GET请求:

In this case it will generate a GET request like this:

http://localhost/Home/Validate?HouseState.Name=CA

问题在于它期望服务器中的变量为House.Name在C#中是无效的变量名.

The problem is that it expect my variable in the server be House.Name witch is an invalid variable name in C#.

是否可以在客户端中自定义此变量或为服务器中的变量创建别名?我试过使用FormCollection,它可以正常工作,但远非完美.

Is there a way I could customize this variable in the client or make an alias for the variable in the server? I've tried use FormCollection and it worked but is far from perfect.

public JsonResult Validate(FormCollection form)
{
    ...
}

我想要这样一种工作方式:

I wanted some way to it work like this:

public JsonResult Validate(string stateName)
{
    ...
}

推荐答案

您可以使用BindAttributePrefix属性有效地剥离"前缀.

You can use the Prefix property of BindAttribute to effectively 'strip' the prefix.

public JsonResult Validate([Bind(Prefix="HouseState.Name")]string Name)

所以name="HouseState.Name"在绑定时变成Name

这篇关于带有无效变量名的jQuery验证远程:如何解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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