我想用AJAX发布以将数据存储在数据库中,我正在使用ADO.Net。但是,它不起作用。
这是我的代码:
控制器
[HttpPost]
public JsonResult InsertScore(ScoresQ scores)
{
db.ScoresQs.Add(scores);
db.SaveChanges();
return Json("true", JsonRequestBehavior.AllowGet);
}
型号
public partial class ScoresQ
{ [Key]
public int id { get; set; }
private DateTime? month = null;
public DateTime DateCreated
{
get
{
return this.month.HasValue
? this.month.Value
: DateTime.Now;
}
set { this.month = value; }
}
public Nullable<int> status { get; set; }
public Nullable<int> score { get; set; }
}
AJAX POST
js中的这个ajax。不在视图中
function showScore(data) {
quiz.style.display = "none";
scoreBlock.style.display = "block";
scoreBlock.innerHTML = "<p> You scored " + score + " out of " + data.length + "</p>";
console.log(score);
if (score < 4) {
scoreMessage.innerHTML = "<p>Not so good! Time for some revision.</p>";
}
else if (score < 8) {
scoreMessage.innerHTML = "<p>Pretty good! But still room for improvement.</p>"
}
else {
scoreMessage.innerHTML = "<p>Great work! You really know your birds!</p>"
}
$.ajax({
type: "post",
url: "Home/InsertScore",
dataType: "json",
data: { score: score, status: 1},
success: function (data) {
console.log("Success");
},
error: function () {
console.log("error");
}
});
scoreMessage.style.display = "block";
quizAgain.style.display = "block";
}
这里是错误
System.InvalidOperationException:"实体类型ScoresQ不是当前上下文的模型的一部分。">
如错误所示,问题出在将对象添加到数据库的代码中。共享该代码以进行进一步分析。
您从JQuery发送的模型与Controller中的模型不匹配。尝试以这种方式修改它:
$.ajax({
type: "post",
url: "Home/InsertScore",
dataType: "json",
data: {model.month: month, model.DateCreated: date, model.score: score, model.status: 1},
success: function (data) {
console.log("Success");
},
error: function () {
console.log("error");
}
});
我已经修复了错误,我只是更改了类似的ajax代码
$.ajax({
type: "post",
url: "Home/InsertScore",
dataType: "json",
data:
{"score": score, "status": 1},
success: function (data) {
console.log("Success");
},
error: function () {
console.log("error");
}
});
您在ajax中单独传递变量,需要作为对象传递,
试试下面的代码,
var scores = {score: score, status: 1};
$.ajax({
type: "post",
url: "Home/InsertScore",
dataType: "json",
data: scores ,
success: function (data) {
console.log("Success");
},
error: function () {
console.log("error");
}
});