Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

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

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)
{
    ...
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...