jQuery 使用无效变量名验证远程:如何修复?

jQuery Validation remote with invalid variable name: How to fix?

我正在使用 remote 验证和 jQuery 验证。

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

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

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

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

@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 请求:

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

问题是它期望我在服务器中的变量是 House.Name 在 C# 中是一个无效的变量名。

有没有办法在客户端自定义这个变量或者在服务器中为这个变量创建一个别名?我已经尝试使用 FormCollection 并且它有效但远非完美。

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

我想要一些方法让它像这样工作:

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

您可以使用 BindAttributePrefix 属性 来有效地 'strip' 前缀。

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

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