c# - Message: Invalid JSON primitive: ajax jquery method with Webmethod

ID : 274353

viewed : 35

Tags : c#jqueryasp.netasp.net-ajaxc#





Top 3 Answer for c# - Message: Invalid JSON primitive: ajax jquery method with Webmethod

vote vote

90

With your contentType: 'application/json; charset=utf-8' you are claiming that you will send JSON but currently your data property is not holding JSON.

You need to transform your data to JSON with the JSON.stringify method:

So change your data property to:

data: JSON.stringify({     "projectSoid": ProjectId,     "startDate": StartDate,     "endDate": EndDate,     "clientManager": ClientManager }), 

You should note that the JSON.stringify method is not natively supported in older browsers so you may need to provide an implementation with using one of the various libraries like:

Douglas Crockford's JSON2 library.

vote vote

82

Javascript at Client side

 var items = [{ projectSoid: ProjectId, startDate: StartDate, endDate: EndDate, clientManager: ClientManager }];                      $.ajax({                        url: '"../Member/Home.aspx/SaveClient',                        type: "POST",                        data: JSON.stringify({ items: items }),                         //data:  JSON.stringify("{DocKey : '" + DocKey + "',highlightText: '" +  JSON.stringify(text) + "',pageNo: '" + pgNo + "',left: '" + left + "',top: '" + top + "',width: '" + width + "',height: '" + height + "'}"),                         //data: "{DocKey\":\""+ DocKey+"\",\"highlightText\":\""+ text +"\",\"pageNo\":\""+pgNo+"\",\"left\":\""+left+"\",\"top\":\""+top+",\"width\":\""+width+"\",\"height\":\""+ height +"}}",                        // data: "{DocKey : '" + DocKey + "',highlightText: '" + text + "',pageNo: '" + pgNo + "',left: '" + left + "',top: '" + top + "',width: '" + width + "',height: '" + height + "'}",                        contentType: "application/json; charset=utf-8",                        dataType: "json",                        beforeSend: function () {                            alert("Start!!! ");                        },                        success: function (data) {                            alert("Save data Successfully");                        },                        failure: function (msg) { alert("Sorry!!! "); evt.obj.deleteObject(); },                        async: false                     }); 

Web Method at Code behind

[WebMethod]         public static string SaveClient(object items)       {      List<object> lstItems = new     JavaScriptSerializer().ConvertToType<List<object>>(items);    Dictionary<string, object> dic = (Dictionary<string, object>)lstItems[0];      } 
vote vote

74

Top 3 video Explaining c# - Message: Invalid JSON primitive: ajax jquery method with Webmethod







Related QUESTION?