POST an array of objects with $.ajax to C# WebMethod

//Create JS method invoking your C# WebMethod (example: getNames)

    function getFstNames() {
        var myObj = [
            { 'fstName': 'name 1', 'lastName':'last name 1', 'age': 32 }
          , { 'fstName': 'name 2', 'lastName':'last name 1', 'age': 33 }
        ];

        var postData = JSON.stringify({ lst: myObj });
        console.log(postData);

        $.ajax({
            type: "POST",
            url: "http://yourUrl.aspx/getNames",
            data: postData,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                alert(response.d);
            },
            failure: function (msg) {
                alert(msg.d);
            }
        });
    }


//Your WebMethod

        [WebMethod]
        public static string getNames(IEnumerable<object> lst)
        {
            string names = "";
            try
            {
                foreach (object item in lst)
                {
                    Type myType = item.GetType();
                    IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());

                    foreach (PropertyInfo prop in props)
                    {
                        if(prop.Name == "Values")
                        {
                            Dictionary<string, object> dic = item as Dictionary<string, object>;
                            names += dic["fstName"];
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                 names = "-1";
            }
            return names;
        }

Comments

Popular posts from this blog

Download file from input type file javascript

Work with array of objects in browser local storage