Home Jquery Ajax POST to C# WebMethod Errors with "Invalid JSON primitive: System.Object."
Reply: 0

Jquery Ajax POST to C# WebMethod Errors with "Invalid JSON primitive: System.Object."

user2499
1#
user2499 Published in June 25, 2018, 4:10 am

Morning all. I've been trying to do this for weeks now but keep going in circles. I have a simple jQuery Ajax function that POSTS Data to a c# function in the code behind.

Basically want to pass a list of selected checkbox fields to be processed. When I submit it, I can see the request being made and the json being sent:

{"item":["Section1","Section2","Section2Sub1","Section2Sub2","Section3"]}

It gets to the server side but when trying to deserialize it, it kicks me back the following error message:

"Invalid JSON primitive: System.Object."

var selection = serializer.Deserialize<string>(item.ToString());

Here's my code snippet:

 

client side
 $("#Submit").click(function (e) {

                    var count = 0;
                    var countChecked = 0;

                    areaObj = [];
                    $('input[type=checkbox]').each(function () {
                        count++;
                        if (this.checked) {
                            //countChecked++;
                            //tmp = {
                            //    "Area": $(this).attr("id")
                            //};
                            areaObj.push($(this).attr("id"));
                        }
                    });
                 });

 function subClick(item) {

            $.ajax({
                type: "POST",
                url: "Default.aspx/SubData",
                data: JSON.stringify({ item: item }),
                //data: "{'item':" + JSON.stringify(item) + "}",
                dataType: "json",
                contentType: "application/json; charset=utf-8"
            });
        };

c# Default.aspx.cs
[WebMethod]
        public static string SubData(Selection item)
        {
            var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            //ERROR OCCURS HERE
            var selection = serializer.Deserialize(item.ToString());

            return "this is successful";
        }

 public class Selection
    {
        public string Title { get; set; }
        public string Description { get; set; }
        public List KeyValues { get; set; }
    }
    public class KeyValues
    {
        public int AreaID { get; set; }
        public string Area { get; set; }
        public int Value { get; set; }
    }

Can anyone offer any pointers on what is going wrong?

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.319981 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO