c# - Ajax处理中的"Invalid JSON primitive"

标签 c# jquery webmethod

我在 jQuery 的 ajax 调用中遇到错误。

这是我的 jQuery 函数:

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");
        }
    });
}

这是我的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";
}

有人能告诉我我的代码有什么问题吗?

我收到这个错误:

{
    "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"
}

最佳答案

猜猜变量 json 之后包含什么

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

如果它是一个有效的 json 对象,如 {"foo":"foovalue", "bar":"barvalue"} 那么 jQuery 可能不会将它作为 json 数据发送,而是将其序列化为 foor=foovalue&bar=barvalue 因此你得到错误 "Invalid JSON primitive: foo"

尝试将数据设置为字符串

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

这样 jQuery 应该单独保留数据并将字符串按原样发送到服务器,这应该允许 ASP.NET 解析 json 服务器端。

关于c# - Ajax处理中的"Invalid JSON primitive",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2445874/

相关文章:

c# - Delegate with parameters... 作为参数

c# - 使用标题和行列表创建 View

javascript - 滚动到页面上值 = 'x' 的位置

jquery - Ajax 调用 web 服务,返回 HTML 未能应用 CSS

c# - HttpClient .Result 在使用 [WebMethod] 属性时挂起

c# - 如何找到相机视野所包含的区域?

Javascript 方法链

jquery - 在 jQuery UI 对话框确认框中使用验证码

c# - 页面 Web 方法在 Web 服务方法完美调用的 Ajax 调用中不起作用

c# - 使用 Replace() 从开头删除引号会将它们全部删除