【问题标题】:how to pass array to mvc using ajax in asp.net如何在asp.net中使用ajax将数组传递给mvc
【发布时间】:2020-11-25 05:31:20
【问题描述】:

如何将mvc中的数组传递到sql server中?我需要保存每个问题的分数,所以我使用 ajax 和 jquery 来做,但它只保存列表数组的一个数据。数组的变量是result,需要在eachscore中赋值。这里是我的代码。

  public partial class Score
    {
        public int idScore { get; set; }
        public Nullable<System.DateTime> date { get; set; }
        public Nullable<int> status { get; set; }
        public Nullable<int> IdMaterial { get; set; }
        public Nullable<int> score { get; set; }
        public string username { get; set; }
        public Nullable<int> eachscore { get; set; }
    
        public virtual Learning Learning { get; set; }
    }

Ajax

function showScore(data, id, ...result) {
    
        $.ajax({
            type: "post",
            url: "/Home/InsertScore",
            dataType: "json",
            traditional: true,
            data:
            { "score": score, "status": 1, "IdMaterial": id, "eachscore": result}           
            success: function (data) {
                console.log("Success");
            },
            error: function () {
                console.log("error");
            }
    });
}

控制器

 public ActionResult InsertScore([Bind(Include = "idScore,date,status,IdMaterial, score, username,eachscore")] Score s)
        {
            if (Session["UserName"] != null)
            {
                var user = Session["UserName"].ToString();
                s.username = user;
                db.Scores.Add(s);
                db.SaveChanges();
                return Json("true", JsonRequestBehavior.AllowGet);
            }
            else
            {
                return RedirectToAction("Login", "Account");
            }
        }

【问题讨论】:

    标签: c# jquery ajax asp.net-mvc


    【解决方案1】:

    在 AJAX 请求中传递数组

     var ScoreArray= [];
    

    使用 For 循环推送数据。

    ScoreArray.push({
             idScore  : 1,
             score    : 10,
             Others key 
    
          });
    

    Ajax Pass 数组

    data: "{ 'lstScoreArray':" + JSON.stringify(ScoreArray) + "}"
    

    控制器

    public ActionResult InsertScore(List&lt;Score&gt;lstScoreArray) { 你的代码...... }

    【讨论】:

    • 但是,唯一的数组变量是 eachscore ,而不是所有变量。 result 需要分配到eachscore
    • 我只想要eachscore 持有列表数组保存在数据库中。其余变量应该不包含在数组中。根据您的建议,您将所有变量存储在数组中。
    • 这就像我传递其他变量并将我的变量数组传递给 mvc。
    • 您必须使用逗号分隔值传递每个分数。 EX: 10,20,30etc...更改控制器端的代码。添加新参数,它是调用字符串 eachscore。并使用逗号拆分字符串并使用循环将值存储在数据库中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-10
    • 2018-09-10
    • 2021-04-14
    • 2011-07-26
    • 2011-12-16
    • 2017-02-18
    相关资源
    最近更新 更多