亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將 JSON 字符串發送到我的后端代碼以將其添加到我的數據庫中,但它沒有添加任何內容

將 JSON 字符串發送到我的后端代碼以將其添加到我的數據庫中,但它沒有添加任何內容

C#
守候你守候我 2021-08-29 17:44:34
我已經被這個問題困住了一段時間我正在嘗試通過 jQuery/AJAX 向我的數據庫添加一個對象。顯然,沒有錯誤,但它沒有向我的數據庫添加任何內容。這是我的 JS/JQuery 代碼:var student = new Object();student.Name = $("#txtNameAdd").val();student.Age = $("#txtAgeAdd").val();student.Email = $("#txtEmailAdd").val();$.ajax({    type: "POST",    url: "Default.aspx/AddStudent",    data: "{'studentJSONString':'" + JSON.stringify(student) + "'}",    success: function (response) {        $("#lblSuccessAdd").text("Success!");        $("#lblSuccessAdd").css("display", "block");    },    error: function (response) {        alert(response.responseJSON);    }});我的 JS 代碼指向我在 Default.aspx 頁面代碼中的這段代碼:    [WebMethod]    public static void AddStudent(string studentJSONString)    {        JavaScriptSerializer converter = new JavaScriptSerializer();        Student a = converter.Deserialize<Student>(studentJSONString);        WebMethods.AddStudent(a);    }它指向我的 WebMethods.cs 類中的這段代碼    [WebMethod]    public static void AddStudent(Student student)    {        MasterStudent master = new MasterStudent();        master.AddStudent(student);    }最后轉到我的類庫并在 MasterStudent 中使用此方法完成:    public void AddStudent(Student student)    {        if (string.IsNullOrWhiteSpace(student.Name))        {            throw new Exception("There's no name");        }        if (string.IsNullOrWhiteSpace(student.Email))        {            throw new Exception("There's no email");        }        using (studentEntities model = new studentEntities())        {            model.student.Add(student);            model.SaveChanges();        }    }我運行代碼,控制臺沒有記錄任何問題,但它也沒有做任何事情。我已經在 Forms 應用程序上運行了非常相似的代碼,沒有出現任何問題,所以我現在有點不知所措。有誰知道為什么它總是失???
查看完整描述

3 回答

?
富國滬深

TA貢獻1790條經驗 獲得超9個贊

所以我在發布我的問題后不久確實找到了解決方案,我將 JQuery AJAX 調用更改為如下所示:


    $.ajax({

    type: "POST",

    url: "Default.aspx/AddStudent",

    data: "{'studentJSONString':'" + JSON.stringify(student) + "'}",

    contentType: "application/json; charset=utf-8",

    dataType: "json",

    success: function (response) {

        $("#lblSuccessAdd").text("Success!");

        $("#lblSuccessAdd").css("display", "block");

    },

    error: function (response) {

        $("#lblErrorAdd").text(response.responseJSON.Message);

        $("#lblErrorAdd").css("display", "block");

    }

});

它現在確實有效!所以無論是 dataType 還是 contentType 對我想要做的事情都非常重要



查看完整回答
反對 回復 2021-08-29
?
FFIVE

TA貢獻1797條經驗 獲得超6個贊

您是否嘗試將調試器附加到它并在 model.SaveChanges() 之前驗證學生對象不為空?

首先嘗試調試并驗證學生字符串是否正在轉換為實際的學生對象。

如果是,則嘗試分析數據庫并驗證發出的任何命令。


查看完整回答
反對 回復 2021-08-29
  • 3 回答
  • 0 關注
  • 221 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號