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

查看:19
本文介绍了带有无效变量名的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

so name="HouseState.Name" becomes just Name when binding

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

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