ASP.NET WebForms & jQuery Validate's remote method

╄→гoц情女王★ 提交于 2019-12-25 02:55:36

问题


Can anyone please tell me how I can get an ASP.NET WebMethod to return correctly-formatted data for display by jQuery Validate? Here's my code:

Client-side code

$('#txtUName').rules('add', {
    remote: {
        type: 'POST',
        url: 'Register.aspx/ValidateUserNameOrEmail',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({
            'data' : $('#txtUName').val(),
            'valUser' : true
        }),
        dataFilter: function(result) {
            return $.parseJSON(result).d;
        },
        dataType: 'json'
    }
});

Server-side code

[WebMethod]
public static object ValidateUserNameOrEmail(string data, bool valUser)
{
    var col = valUser ? "userName" : "email";
    var label = valUser ? "username" : "email address";

    using (var conn = new SqlConnection(dbConn))
    using (var comm = new SqlCommand("", conn))
    {
        conn.Open();
        comm.CommandText = "SELECT userId FROM [dbo]." +
            "[User] WHERE " + col + " = '" + data + "'";
        if (comm.ExecuteScalar() != null)
        {
            // Entered username or email already exists in the DB
            return "A user with that " + label + " already " +
                "exists. Please enter a unique " + label + ".";
        }
    }
    return true;
}

tl;dr - Should I just give up on the fact that this is supposed to just work, and use a custom remote message? This should work, since I can see that false is definitely returned from a later call to element.valid() when the username is already taken. But I'd really like to avoid having to specify a custom message if possible.

EDIT: Indeed the above solution works, so I'll use it for now, but please read on and suggest a better solution if you can!

Stepping through both pieces of code, I can see that everything gets called and returned wonderfully, but jQuery Validate just refuses to display the damn error!

According to the official docs:

The response is evaluated as JSON and must be true for valid elements, and can be any false, undefined or null for invalid elements, using the default message; or a string, eg. "That name is already taken, try peter123 instead" to display as the error message.

So what am I doing wrong?? As you can clearly see above, I return true in the case of success or an appropriate error message string otherwise, just like the docs say I should (well kind-of; see below).

According to those docs and Asp.Net WebForm JQuery remote Validation, I should be returning a JSON object from the server, but I don't see how that would make a difference when I'm parsing it into JSON on the client, to no avail. I would try the solution suggested in Jeff Siver's comment, but I'm guessing that's for MVC, since the Sys namespace doesn't exist on my system.

Sherif Ahmed's answer to jQuery Validator#remote with ASP.NET WebForms is almost functionally-identical to my code, yet I'm getting a completely different result!

I gave up on the suggested StackOverflow posts after these two...my situation seems to be very-slightly-yet-significantly different to them all.

EDIT for @Sparky - Hi and thanks for replying. The first post I linked to does indeed mention using the JavaScriptSerializer class to return data in the proper format, so my apologies for not seeing that earlier. However, that isn't the answer you linked to. The answer you linked to (and that I read) mentions some unknown Json class...as Melursus says there:

Can you provide me an example of how I can return a JSON object because I didn't find this namespace. I didn't find the ActionResult namespace either. So, I don't understand how I can use the proposed solution.

I initially saw that and stopped reading, but your comment prompted me to do further research and find the JavaScriptSerializer solution that may actually work. I'll give it a go and let you know :-)

来源:https://stackoverflow.com/questions/29474043/asp-net-webforms-jquery-validates-remote-method

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