【发布时间】:2018-12-02 05:15:49
【问题描述】:
我已经被这个问题困扰了很久
我正在尝试通过 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 应用程序上运行了非常相似的代码,没有任何问题,所以我现在有点陷入困境。有谁知道为什么它总是失败?
【问题讨论】:
-
不要在问题内回答你的问题。我们为此提供了答案。
标签: javascript c# asp.net json ajax