"Invalid JSON primitive" in Ajax processing

C#JqueryWebmethod

C# Problem Overview


I am getting an error in an ajax call from jQuery.

Here is my jQuery function:

function DeleteItem(RecordId, UId, XmlName, ItemType, UserProfileId) {
    var obj = {
        RecordId: RecordId,
        UserId: UId,
        UserProfileId: UserProfileId,
        ItemType: ItemType,
        FileName: XmlName
    };
    var json = Sys.Serialization.JavaScriptSerializer.serialize(obj);

    $.ajax({
        type: "POST",
        url: "EditUserProfile.aspx/DeleteRecord",
        data: json,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: true,
        cache: false,
        success: function(msg) {
            if (msg.d != null) {
                RefreshData(ItemType, msg.d);
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert("error occured during deleting");
        }
    });
}

and this is my WebMethod:

[WebMethod]
public static string DeleteRecord(Int64 RecordId, Int64 UserId, Int64 UserProfileId, string ItemType, string FileName) {
    try {
        string FilePath = HttpContext.Current.Server.MapPath(FileName);

        XDocument xmldoc = XDocument.Load(FilePath);
        XElement Xelm = xmldoc.Element("UserProfile");
        XElement parentElement = Xelm.XPathSelectElement(ItemType + "/Fields");

        (from BO in parentElement.Descendants("Record")
         where BO.Element("Id").Attribute("value").Value == RecordId.ToString()
         select BO).Remove();
        XDocument xdoc = XDocument.Parse(Xelm.ToString(), LoadOptions.PreserveWhitespace);
        xdoc.Save(FilePath);

        UserInfoHandler obj = new UserInfoHandler();
        return obj.GetHTML(UserId, UserProfileId, FileName, ItemType, RecordId, Xelm).ToString();
    } catch (Exception ex) {
        HandleException.LogError(ex, "EditUserProfile.aspx", "DeleteRecord");
    }
    return "success";
}

Can anybody please tell me what's wrong in my code?

I am getting this error:

{
    "Message":"Invalid JSON primitive: RecordId.",
    "StackTrace":"
       at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()
       at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)
       at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)
       at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)
       at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)
       at System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext context, JavaScriptSerializer serializer)
       at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)
       at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)",
    "ExceptionType":"System.ArgumentException"
}

C# Solutions


Solution 1 - C#

Just a guess what does the variable json contain after

var json = Sys.Serialization.JavaScriptSerializer.serialize(obj);?

If it is a valid json object like {"foo":"foovalue", "bar":"barvalue"} then jQuery might not send it as json data but instead serialize it to foor=foovalue&bar=barvalue thus you get the error "Invalid JSON primitive: foo"

Try instead setting the data as string

$.ajax({
    ...
    data: '{"foo":"foovalue", "bar":"barvalue"}', //note the additional quotation marks
    ...
})

This way jQuery should leave the data alone and send the string as is to the server which should allow ASP.NET to parse the json server side.

Solution 2 - C#

Using

data : JSON.stringify(obj)

in the above situation would have worked I believe.

Note: You should add json2.js library all browsers don't support that JSON object (IE7-) https://stackoverflow.com/questions/552135/difference-between-json-js-and-json2-js

Solution 3 - C#

it's working something like this

data: JSON.stringify({'id':x}),

Solution 4 - C#

As noted by jitter, the $.ajax function serializes any object/array used as the data parameter into a url-encoded format. Oddly enough, the dataType parameter only applies to the response from the server - and not to any data in the request.

After encountering the same problem I downloaded and used the jquery-json plugin to correctly encode the request data to the ScriptService. Then, used the $.toJSON function to encode the desired arguments to send to the server:

$.ajax({
    type: "POST",
    url: "EditUserProfile.aspx/DeleteRecord",
    data: $.toJSON(obj),
    contentType: "application/json; charset=utf-8",
    dataType: "json"
    ....
});

Solution 5 - C#

Jquery Ajax will default send the data as query string parameters form like:

RecordId=456&UserId=123

unless the processData option is set to false, in which case it will sent as object to the server.

  • contentType option is for the server that in which format client has sent the data.

  • dataType option is for the server which tells that what type of data client is expecting back from the server.

> Don't specify contentType so that server will parse them as query > String parameters not as json.

OR

> Use contentType as 'application/json; charset=utf-8' and use JSON.stringify(object) so that server would be able to deserialize json from string.

Solution 6 - C#

I guess @jitter was right in his guess, but his solution didn't work for me.

Here is what it did work:

$.ajax({
    ...
    data: "{ intFoo: " + intFoo + " }",
    ...
});

I haven't tried but i think if the parametter is a string it should be like this:

$.ajax({
    ...
    data: "{ intFoo: " + intFoo + ", strBar: '" + strBar + "' }",
    ...
});

Solution 7 - C#

I was facing the same issue, what i came with good solution is as below:

Try this...

$.ajax({
    type: "POST",
    url: "EditUserProfile.aspx/DeleteRecord",
    data: '{RecordId: ' + RecordId + ', UserId: ' + UId + ', UserProfileId:' + UserProfileId + ', ItemType: \'' + ItemType + '\', FileName: '\' + XmlName + '\'}',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    async: true,
    cache: false,
    success: function(msg) {
        if (msg.d != null) {
            RefreshData(ItemType, msg.d);
        }
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert("error occured during deleting");
    }
});

Please note here for string type parameter i have used (') escape sequence character for denoting it as string value.

Solution 8 - C#

Here dataTpe is "json" so, data/reqParam must be in the form of string while calling API, many as much as object as you want but at last inside $.ajax's data stringify the object.

             let person= {  name: 'john',
                age: 22
            };

           var personStr = JSON.stringify(person); 

            $.ajax({
                url: "@Url.Action("METHOD", "CONTROLLER")",
                type: "POST",
                data: JSON.stringify( { param1: personStr } ),
                contentType: "application/json;charset=utf-8",
                dataType: "json",
        success: function (response) {

            console.log("Success");
                      
        },
        error: function (error) {
            console.log("error found",error);
        }
    });

OR,

       $.ajax({
                url: "@Url.Action("METHOD", "CONTROLLER")",
                type: "POST",
                data: personStr,
                contentType: "application/json;charset=utf-8",
                dataType: "json",
        success: function (response) {

            console.log("Success");
                      
        },
        error: function (error) {
            console.log("error found",error);
        }
    });

Solution 9 - C#

If manually formatting JSON, there is a very handy validator here: jsonlint.com

Use double quotes instead of single quotes:

Invalid:
{
    'project': 'a2ab6ef4-1a8c-40cd-b561-2112b6baffd6',
    'franchise': '110bcca5-cc74-416a-9e2a-f90a8c5f63a0'
}
Valid:
{
    "project": "a2ab6ef4-1a8c-40cd-b561-2112b6baffd6",
    "franchise": "18e899f6-dd71-41b7-8c45-5dc0919679ef"
}

Solution 10 - C#

On the Server, to Serialize/Deserialize json to custom objects:

public static string Serialize<T>(T obj)
{
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
    MemoryStream ms = new MemoryStream();
    serializer.WriteObject(ms, obj);
    string retVal = Encoding.UTF8.GetString(ms.ToArray());
    return retVal;
}

public static T Deserialize<T>(string json)
{
    T obj = Activator.CreateInstance<T>();
    MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
    obj = (T)serializer.ReadObject(ms);
    ms.Close();
    return obj;
}

Solution 11 - C#

I had the same issue. I was calling parent page "Save" from Popup window Close. Found that I was using ClientIDMode="Static" on both parent and popup page with same control id. Removing ClientIDMode="Static" from one of the pages solved the issue.

Solution 12 - C#

these answers just had me bouncing back and forth between invalid parameter and missing parameter.

this worked for me , just wrap string variables in quotes...

data: { RecordId: RecordId,
            UserId: UId,
            UserProfileId: UserProfileId,
            ItemType: '"' +  ItemType + '"',
            FileName: '"' +  XmlName + '"'
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRadhiView Question on Stackoverflow
Solution 1 - C#jitterView Answer on Stackoverflow
Solution 2 - C#AndrewView Answer on Stackoverflow
Solution 3 - C#Jessica SaenzView Answer on Stackoverflow
Solution 4 - C#leepowersView Answer on Stackoverflow
Solution 5 - C#T GuptaView Answer on Stackoverflow
Solution 6 - C#DiegoView Answer on Stackoverflow
Solution 7 - C#Sohel PathanView Answer on Stackoverflow
Solution 8 - C#Gaurav BasnetView Answer on Stackoverflow
Solution 9 - C#Daniel de ZwaanView Answer on Stackoverflow
Solution 10 - C#Ioannis SuarezView Answer on Stackoverflow
Solution 11 - C#Mintu GoyalView Answer on Stackoverflow
Solution 12 - C#vernmicView Answer on Stackoverflow