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

戏子无情 提交于 2019-12-29 02:02:28

问题


I'm using remote validation with jQuery Validation.

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

In my *.cshtml I have this:

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

I'm adding validation with this:

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

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

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

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

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

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)
{
    ...
}

回答1:


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

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

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



来源:https://stackoverflow.com/questions/36839202/jquery-validation-remote-with-invalid-variable-name-how-to-fix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!