c# - ASP.NET MVC 4 : error when making Ajax call to controller to update SQL Server database

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

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

System.Data.SqlClient.SqlException was unhandled by user code
HResult=-2146232060
Message=The parameterized query '(@ID int,@AlertStatus nvarchar(4000),@Comment nvarchar(4000))UPD' expects the parameter '@AlertStatus', which was not supplied.
Source=.Net SqlClient Data Provider


在进一步的研究中,我发现可以使用?? DBNull.Value避免这种情况,但是我不想将列更新为NULL。我怀疑错误的原因是在更新函数中我的Ajax调用中,数据没有发送到 Controller (数据:'{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");
            }
        })
    });
Controller :
    [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; }

}
}

最佳答案

通过分而治之应该很简单。
使用Chrome或任何其他浏览器,在设置task的行上设置一个断点,注释并检查任务对象以查看AlertStatus在该点是否具有值。然后切换到网络标签,然后继续单步执行代码。检查发送到 Controller 的请求的有效负载,并查看其中是否还包含AlertStatus。如果一切都很好,那么问题出在服务器端。如果不是,问题出在您的客户端。
然后在开始时在 Controller 中设置一个断点,并在其中检查任务对象中的AlertStatus。如果它为null,则Modelbinder出了点问题。如果它具有值,那么您应该擅长于此,而问题出在那之后。
另外,如果您不想为该值允许null,则应在尝试将其提交到数据库之前进行一些验证,并使用典型的MVC验证元素进行验证,然后将400错误的请求返回给客户端。验证的一部分可能在Task类中,我们目前无法看到。
祝好运!

关于c# - ASP.NET MVC 4 : error when making Ajax call to controller to update SQL Server database,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65258492/

相关文章:

c# - 将自定义 DialogPreference 添加到 xml 文件

c# - Linq EF - 如何通过优化查询从数据库中收集特定客户的所有账户、卡、贷款等?

c# - 了解协程的执行

sql-server - SQL Server 2005中的tran和transaction有什么区别

sql - 如何使用 XQuery/SQL 进行解码等?

javascript - Chrome 'please match the requested format' 验证消息

javascript - 如何在 C# 中的类库中运行 npm 命令

SQL Server 创建用户定义的表类型时架构无法正常工作

c# - EntityFramework.dll 中出现 'System.InvalidOperationException' 类型的异常,但未在用户代码中处理

asp.net-mvc-4 - 使用 Web Api 和结构图依赖注入(inject)