samedi 11 juin 2016

Using JQuery to POST data to a C# web service


I posted this on 'Programmers' and was told it belongs here, so here goes...

I have an ASP.NET Web Form in which I am using JQuery's .dialog() method to display a registration form. Here is the dialog code:

$("#register").dialog({
                appendTo: "form",
                autoOpen: false,
                show: { effect: "fadeIn" },
                hide: { effect: "fadeOut" },
                modal: true,
                draggable: false,
                minWidth: 750,
                minHeight: 400,
                resizable: false,
                dialogClass: "no-close",
                buttons:
                    [
                        {
                            class: "firstButton",
                            text: "Register Me",
                            click: function () {
                                var formData = $.param($('#register').find(':input').serializeArray());
                                alert(formData);
                                $.ajax({
                                    url: "Services/members.asmx/ValidateUser",
                                    timeout: 30000,
                                    type: "POST",
                                    data: "{ 'formInfo': '" + formData + "' }",
                                    dataType: "json",
                                    contentType: "application/json; charset=utf-8",
                                    error: function (jqXHR, textStatus, errorThrown) {
                                        if (textStatus == "error") {
                                            $("#spStatus").css('class', 'textRed')
                                                .text("An error has occurred: " + jqXHR.status
                                            + " " + jqXHR.statusText);
                                        }
                                    },
                                    success: function (data) {
                                        $("#spStatus").css('class', 'textGreen').text(data.d);
                                        //$(this).dialog("close");
                                    }
                                })
                            }
                        },
                        {
                            class: "lastButton",
                            text: "Maybe Later",
                            click: function () {
                                $(this).dialog("close");
                            }
                        }
                    ]
            });

The registration form itself is comprised of DIV tags. I can't use a form element because the ASP.NET page itself already has one, and you can't nest forms, so I have to do this using DIVs, which I'm okay with, except that it causes a problem when I need to serialize the form data to send it to the web service. Since I'm not using a form wrapper for it, I found a workaround for serializing the form data into a querystring-encoded format, which works:

var formData = $.param($('#register').find(':input'));

The problem is, I can't just pass this straight to the web service as a string, because the web service throws an error stating that I'm not passing a value in for the named input parameter. The web service (just stubbed out for testing purposes) is declared as so:

[WebMethod]
public string ValidateUser(string formInfo)
{
    NameValueCollection formFields = HttpUtility.ParseQueryString(userName);
    int fields = formFields.Count;
    return formFields["userName"].ToString();
}

The only way this works is how it's set up right now, where I have to use a bit of a hack to get the web service to accept the string. First, I capture the form data:

var formData = $.param($('#register').find(':input').serializeArray());

Then I prepend that string so that the web service will accept the input string:

data: "{ 'formInfo': '" + formData + "' }",

You can see from the web service method's code how I have to process the incoming string. Now, all of this works, but it seems kludgy and not the right way to go about it. I've tried every alternative I could find, but nothing seems to get me where I need to be.

In short, I want to serialize the form data (remember, it's contained in a DIV element, not a form element) into a JSON string that I can pass to the web service. Then I need the web service to recognize the JSON data so I can parse and process it.

Help would be greatly appreciated!


Aucun commentaire:

Enregistrer un commentaire