微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Ajax POST到Asp.net MVC

如何解决Ajax POST到Asp.net MVC

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。