【问题标题】:Asp.Net Mvc 4 jQuery Ajax Insert DataAsp.Net Mvc 4 jQuery Ajax 插入数据
【发布时间】:2015-07-08 14:45:17
【问题描述】:

我是 Asp.Net Mvc 的新手。我正在尝试使用 jQuery ajax 将数据插入数据库。它正在插入数据,但也提供错误:

alert('Ajax 调用错误').

代码如下:

JS:

function SaveComment() {
    var author = $("#author").val();
    var comment = $("#comment").val();
    var articleId = $("#HdnArticleId").val();
    $("#commentgif").show();
    $("#btn").attr("disabled", "true");

    $.ajax({
        type: "POST",
        url: "/Home/SaveComment",
        data: "{author:'" + author + "', comment:'" + comment + "', articleId:'" + articleId + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: Success,
        error: function (msg) {
            $("#commentgif").hide();
            alert("Ajax call error!");
            $("#btn").removeAttr("disabled");
        }
    });
}

C#:

[HttpPost]
public ActionResult SaveComment(string author, string comment, int articleId)
{
    CommentBLL CommBLL = new CommentBLL();
    Comment NewComment = new Comment();
    NewComment.ArticleId = articleId;
    NewComment.Content = comment;
    NewComment.IsActive = false;
    NewComment.Name = author;
    NewComment.Date = DateTime.Now;
    CommBLL.Save(NewComment);
    return View();
}

【问题讨论】:

  • 因为success:Success在这种情况下无效,需要给它提供success回调!

标签: jquery ajax model-view-controller


【解决方案1】:

尝试将 SaveComment 方法中的参数作为字符串接收,然后转换 articleId。

【讨论】:

    【解决方案2】:

    您必须在您的操作中将 ActionResult 更改为 JsonResult,因为在您的 ajax 调用中,您需要 JSON 数据:

    dataType: "json",
    

    【讨论】:

      猜你喜欢
      • 2017-08-12
      • 2018-10-03
      • 1970-01-01
      • 2021-05-29
      • 2018-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多