【问题标题】:ASP.NET MVC 4: error when making Ajax call to controller to update SQL Server databaseASP.NET MVC 4:对控制器进行 Ajax 调用以更新 SQL Server 数据库时出错
【发布时间】:2020-12-11 20:55:35
【问题描述】:

我正在尝试使用 ASP.NET MVC 4、jQuery 和 Ajax 更新 SQL Server 中表的记录。但是,每当我单击更新时,都会出现以下错误:

System.Data.SqlClient.SqlException 未被用户代码处理
HResult=-2146232060
Message=参数化查询“(@ID int,@AlertStatus nvarchar(4000),@Comment nvarchar(4000))UPD”需要参数“@AlertStatus”,但未提供该参数。
Source=.Net SqlClient 数据提供者

在进一步的研究中,我发现使用?? DBNull.Value 可以避免这种情况,但是我不想将该列更新为NULL。我怀疑错误的原因是我在更新函数中的 Ajax 调用中没有将数据发送到控制器(数据:'{task:' + JSON.stringify(task) + '}',)。

请查看下面的代码,感谢您的帮助。

jQuery Ajax

    $("body").on("click", "#tblTask .Edit", function () {
        var row = $(this).closest("tr");
        $("td", row).each(function () {
            if ($(this).find("input").length > 0) {
                $(this).find("input").show();
                $(this).find("span").hide();
            }
        });
        row.find(".Update").show();
        row.find(".Cancel").show();
        row.find(".Delete").hide();
        $(this).hide();
    });

    $("body").on("click", "#tblTask .Update", function () {
        var row = $(this).closest("tr");
        $("td", row).each(function () {
            if ($(this).find("input").length > 0) {
                var span = $(this).find("span");
                var input = $(this).find("input");
                span.html(input.val());
                span.show();
                input.hide();
            }
        });
        row.find(".Edit").show();
        row.find(".Delete").hide();
        row.find(".Cancel").hide();
        $(this).hide();

        var task = {};
        task.taskID = row.find(".taskID").find("span").html();
        task.GroupSubsidiary = row.find(".GroupSub").find("span").html();
        task.FunctionName = row.find(".Fname").find("span").html();
        task.FunctionDesc = row.find(".Fdesc").find("span").html();
        task.CheckPeriod = row.find(".Checkp").find("span").html();
        task.Profiledate = row.find(".Pdate").find("span").html();
        task.PeriodDay = row.find(".Pday").find("span").html();
        task.AlertStatus = row.find(".Status").find("span").html();
        task.Comment = row.find(".Comment").find("span").html();
        $.ajax({
            type: 'POST',
            url: "@Url.Action("UpdateTask","Task")",
            data: '{task:' + JSON.stringify(task) + '}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function () {
                alert("Updated Sucessfully");
            },
            error: function () {
                alert("An Error Occured");
            }
        })
    });

控制器:

    [HttpPost]
    public ActionResult UpdateTask(Task tasks)
    {
        string constr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
        string query = "UPDATE AS_AlertsDefinition SET GroupSubsidiary= @GroupSubsidiary, FunctionName= @FunctionName, FunctionDesc= @FunctionDesc, CheckPeriod= @CheckPeriod, Profiledate= @Profiledate, PeriodDay= @PeriodDay, AlertStatus= @AlertStatus, Comment= @Comment WHERE ID= @ID";

        using (SqlConnection sqlcon = new SqlConnection(constr))
        {
            using (SqlCommand sqlcmd = new SqlCommand(query))
            {
                sqlcmd.Parameters.AddWithValue("@ID", tasks.ID);
                sqlcmd.Parameters.AddWithValue("@GroupSubsidiary", tasks.GroupSubsidiary);
                sqlcmd.Parameters.AddWithValue("@FunctionName", tasks.FunctionName);
                sqlcmd.Parameters.AddWithValue("@FunctionDesc", tasks.FunctionDesc);
                sqlcmd.Parameters.AddWithValue("@CheckPeriod", tasks.CheckPeriod);
                sqlcmd.Parameters.AddWithValue("@Profiledate", tasks.Profiledate);
                sqlcmd.Parameters.AddWithValue("@PeriodDay", tasks.PeriodDay);
                sqlcmd.Parameters.AddWithValue("@AlertStatus", tasks.AlertStatus);
                sqlcmd.Parameters.AddWithValue("@Comment", tasks.Comment);
                sqlcmd.Connection = sqlcon;

                sqlcon.Open();
                sqlcmd.ExecuteNonQuery();
                sqlcon.Close();
            }
        }

        return new EmptyResult();
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace AlertNotificationWeb.Models
{
public class Task
{
    public int ID { get; set; }

    public string GroupSubsidiary { get; set; }

    public string FunctionName { get; set; }

    public string FunctionDesc { get; set; }

    public string CheckPeriod { get; set; }

    public string Profiledate { get; set; }

    public int PeriodDay { get; set; }

    public string AlertStatus { get; set; }

    public string Comment { get; set; }

}

}

【问题讨论】:

  • UPDATE 不太可能有问题,但您确实应该使用Parameters.Add 而不是Parameters.AddWithValueAddWithValue is Evil
  • 可以分享一下Task类吗?
  • 通过阅读错误,我认为这可能是变量“@AlertStatus”的问题。检查您的代码并确保您正确设置它并且它不是NULL,因为这可能是这种情况。查找变量值的一个非常好的方法是在错误之前使用 Console.Log(variable) ;)

标签: c# sql-server asp.net-mvc-4 error-handling asp.net-ajax


【解决方案1】:

这应该很容易通过分而治之来解决。

使用 Chrome 或任何其他浏览器,在您设置 task.Comment 的行设置断点并检查任务对象以查看 AlertStatus 在该点是否有值。然后切换到网络选项卡,然后继续单步执行代码。检查发送到控制器的请求的有效负载,看看它是否也有 AlertStatus。如果一切都很好,那么问题出在服务器端。如果不是,问题出在您的客户端。

然后在开始时在控制器中设置断点,并在那里检查任务对象的 AlertStatus。如果它为空,那么模型绑定器出了点问题。如果它有一个价值,那么你应该在这一点上做得很好,问题就在那之后的某个地方。

另外,如果您不想允许该值为 null,则应在尝试将其提交到数据库之前进行一些验证,并使用典型的 MVC 验证元素来执行此操作并将 400 错误请求返回给客户端。部分验证可能在 Task 类中,我们目前看不到。

祝你好运!

【讨论】:

    【解决方案2】:

    我发现了问题,只需要更改:

    var task = {};
            task.taskID = row.find(".taskID").find("span").html();
            task.GroupSubsidiary = row.find(".GroupSub").find("span").html();
            task.FunctionName = row.find(".Fname").find("span").html();
            task.FunctionDesc = row.find(".Fdesc").find("span").html();
            task.CheckPeriod = row.find(".Checkp").find("span").html();
            task.Profiledate = row.find(".Pdate").find("span").html();
            task.PeriodDay = row.find(".Pday").find("span").html();
            task.AlertStatus = row.find(".Status").find("span").html();
            task.Comment = row.find(".Comment").find("span").html();
            $.ajax({
                type: 'POST',
                url: "@Url.Action("UpdateTask","Task")",
                data: '{task:' + JSON.stringify(task) + '}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function () {
                    alert("Updated Sucessfully");
                },
                error: function () {
                    alert("An Error Occured");
                }
            })
        });
    

    收件人:

    var task = JSON.stringify({
                    taskID: row.find(".taskID").find("span").html(),
                    GroupSubsidiary: row.find(".GroupSub").find("span").html(),
                    FunctionName: row.find(".Fname").find("span").html(),
                    FunctionDesc: row.find(".Fdesc").find("span").html(),
                    CheckPeriod: row.find(".Checkp").find("span").html(),
                    Profiledate: row.find(".Pdate").find("span").html(),
                    PeriodDay: row.find(".Pday").find("span").html(),
                    AlertStatus: row.find(".Status").find("input").val(),
                    Comment: row.find(".Comment").find("span").html(),
                });
                $.ajax({
                    type: 'POST',
                    url: "@Url.Action("UpdateTask","Task")",
                    data:  task,
                    contentType: "application/json",
                    dataType: "json",
                    success: function () {
                        alert("Updated Sucessfully");
                    },
                    error: function () {
                        alert("An Error Occured");
                    }
                });
                console.log(task);
            });
    

    【讨论】:

      猜你喜欢
      • 2017-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-17
      • 2023-03-28
      • 2015-10-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多