Monday, December 16, 2013

Sending javaScript array to server side c# via web service call

Sending javaScript array to server side c# via web service call

I wanted to send a collection of attributers for a set of textbox input html controls to the server side via an AJAX call:

Collect the desired elements and place certain properties in an array:
var inputs = new Array();

    $("[class^=txtEdit]").filter(":input").each(function () {

        var i = { 'ClassName': $(this).attr("class"), 'Id': $(this).attr("id"), 'Val': $(this).val() };

        inputs.push(i);

    });






Make the AJAX call:

var serviceUrl = '..//Tools.asmx/SaveEdits';
    $.ajax({
        type: "POST",
        //data: JSON.stringify(inputs),
        data: '{ "elements":' + JSON.stringify(inputs) + '}',
        contentType: "application/json; charset=utf-8",
        url: serviceUrl,
        dataType: "json",
        success: function (response) {
            if (response.d) {
                //TODO: rebind
            }
            else {
                alert("Save Edits Failed");
            }
        },
        error: function (response) {
            alert("failed service call" + serviceUrl);
        }
 
 
    });






Container class on server:

public class HtmlInput
{
    public string ClassName { getset; }
    public string Id { getset; }
    public string Val { getset; }
 
    public HtmlInput()
    {
 
    }
 
    public HtmlInput(string className, string id, string val)
    {
        this.ClassName = className;
        this.Id = id;
        this.Val = val;
    }
 
}




The web method:
/// 
    /// Saves all the inputs (items, appOverdies) using services
    /// 
    /// colecton of html inputs
    /// error string
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string SaveEdits(HtmlInput[] elements)
    {
 
 
        string ret = string.Empty;
 
        try
        {
 
            foreach (HtmlInput txt in elements)
            {
                //DO some stuff
            }
 
 
            return ret;
 
        }
        catch (Exception e)
        {
            //TODO:  log e.message etc.
 
            return ret += e.Message;
        }
 
    }


No comments: