jQuery Validation remote with invalid variable nam

2019-01-20 19:22发布

问题:

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