问题描述
我想用AJAX发布将数据存储在数据库中,并且我正在使用ADO.Net。但是,它不起作用。
这是我的代码:
控制器
obj
模型
[HttpPost]
public JsonResult Insertscore(scoresQ scores)
{
db.scoresQs.Add(scores);
db.SaveChanges();
return Json("true",JsonRequestBehavior.AllowGet);
}
AJAX POST
.js中的这个ajax。不在视图中
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; }
}
这里是错误
system.invalidOperationException:'实体类型scoresQ不是当前上下文模型的一部分。'
解决方法
由于错误显示问题出在将对象添加到db的代码中。分享该代码以进行进一步分析。
,您从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",data:
{"score": score,"status": 1},error: function () {
console.log("error");
}
});
,
您要在ajax中分别传递变量,您需要作为对象传递
尝试以下代码,
var scores = {score: score,status: 1};
$.ajax({
type: "post",data: scores,success: function (data) {
console.log("Success");
},error: function () {
console.log("error");
}
});