更新 ASP.NET Web API 项目中插入的记录

Update the inserted record in ASP.NET Web API project

在我的项目中,我正在插入一名员工,当我的员工被插入时,我的保存按钮 HTML 转向更新,在后端,我使用相同的插入功能来更新我刚才的员工已插入,我的插入功能运行良好,但当我尝试更新同一条记录时,它会在数据库中插入一条新记录,而不是根据插入的 ID 更新数据,我如何根据各自的 ID 更新现有或当前插入的用户。

我不知道为什么我的更新不起作用,为什么我不能在插入用户后立即更新,每次我尝试更新用户时,我最终都会再次插入用户,我应该如何限制我的应用程序一次又一次地插入类似数据,插入和更新按钮是相同的,正如我上面提到的,在插入用户时,我正在将按钮的内部 HTML 从保存更改为更新并使用相同的按钮更新

这是我的完整代码,请告诉我如果我在代码的任何部分有任何错误,非常感谢你们提供的所有帮助

我的存储过程代码:

ALTER PROCEDURE [dbo].[InsEmpOfficialDetails] 
    (@EmpID int = NULL,
     @UserName varchar(500) = NULL,
     @pass varchar(500) = NULL,
     @OfficialEmailAddress varchar(500) = NULL,
     @Department varchar(500) = NULL,
     @RoleID int = NULL,
     @Role varchar(500) = NULL,
     @IsAdmin bit = NULL,
     @Designation varchar(500) = NULL,
     @ReportToID int = NULL,
     @ReportTo varchar(500) = NULL,
     @JoiningDate datetime = NULL,
     @IsPermanent bit = NULL,
     @DateofPermanancy datetime = NULL,
     @IsActive bit = NULL,
     @HiredbyReference bit = NULL,
     @HiredbyReferenceName varchar(500) = NULL,
     @BasicSalary int = NULL,
     @CurrentPicURL nvarchar(max) = NULL
     -- @CreatedBy int,                                 
     -- @CreatedOn datetime,                
     -- @UpdatedOn datetime,                                
     -- @UpdatedBy int                                  
    )
AS
BEGIN
    IF EXISTS (SELECT 1 FROM Employee 
               WHERE UserName = @UserName
                 AND pass = @pass
                 AND OfficialEmailAddress = @OfficialEmailAddress
                 AND Department = @Department
                 AND RoleID = @RoleID
                 AND Role = @Role
                 AND IsAdmin = @IsAdmin
                 AND Designation = @Designation
                 AND ReportToID = @ReportToID
                 AND ReportTo = @ReportTo
                 AND JoiningDate = @JoiningDate
                 AND IsPermanent = @IsPermanent
                 AND DateofPermanancy = @DateofPermanancy
                 AND IsActive = @IsActive
                 AND HiredbyReference = @HiredbyReference
                 AND HiredbyReferenceName = HiredbyReferenceName
                 AND BasicSalary = @BasicSalary
                 AND CurrentPicURL = @CurrentPicURL)
    BEGIN
        UPDATE Employee
        SET UserName = @UserName,
            pass = @pass,
            OfficialEmailAddress = @OfficialEmailAddress,
            Department = @Department,
            RoleID = @RoleID,
            Role = @Role,
            IsAdmin = @IsAdmin,
            Designation = @Designation,
            ReportToID = @ReportToID,
            ReportTo = @ReportTo,
            JoiningDate = @JoiningDate,
            IsPermanent = @IsPermanent,
            DateofPermanancy = @DateofPermanancy,
            IsActive = @IsActive,
            HiredbyReference = @HiredbyReference,
            HiredbyReferenceName = HiredbyReferenceName,
            BasicSalary = @BasicSalary,
            CurrentPicURL = @CurrentPicURL
        WHERE EmpID = @EmpID
    END
    ELSE
    BEGIN
        SET NOCOUNT ON;

    INSERT INTO Employee(UserName, pass,
OfficialEmailAddress,Department,
RoleID, Role, IsAdmin, Designation,
ReportToID, ReportTo, JoiningDate,
IsPermanent, DateofPermanancy, IsActive,
HiredbyReference, HiredbyReferenceName,
BasicSalary, CurrentPicURL)
        VALUES (@UserName, @pass, @OfficialEmailAddress, @Department,
                @RoleID, @Role, @IsAdmin, @Designation,
                @ReportToID, @ReportTo, @JoiningDate,
                @IsPermanent, @DateofPermanancy, @IsActive,
                @HiredbyReference, @HiredbyReferenceName,
                @BasicSalary, @CurrentPicURL)
        SELECT SCOPE_IDENTITY();
    END
END

在输入字段顶部的 HTML 中,我将当前插入的用户 ID 存储在这样的隐藏字段中

<input type="hidden" class="HiddenID" />

我不知道如何在插入后立即使用这个隐藏字段 ID 更新用户,因为正如我提到的,我的插入和更新功能都位于同一个按钮上

我的ajax代码:

$('.empOfficialDetails').click(function (ev) {
    ev.preventDefault();

    var data = new Object();
    data.UserName = $('#username').val();
    data.UPassword = $('#userpass').val();
    data.OfficialEmailAddress = $('#officialemail').val();
    data.Departments = $('#departments :selected').text();
    data.Designation = $('#designation :selected').text();
    data.RoleID = $('#role').val();
    data.Role = $('#role :selected').text();
    data.ReportToID = $('#reportToID').val();
    data.ReportTo = $('#reportTo :selected').text();
    data.JoiningDate = $('#joindate').val();
    data.IsAdmin = $('#isAdmin :selected').val() ? 1 : 0;
    data.IsActive = $('#isActive :selected').val() ? 1 : 0;
    data.IsPermanent = $('#isPermanent :selected').val() ? 1 : 0;
    data.DateofPermanancy = $('#permanantdate').val();
    data.HiredbyReference = $('#hiredbyRef :selected').val() ? 1 : 0;
    data.HiredbyReferenceName = $('#refePersonName').val();
    data.BasicSalary = $('#basicSalary').val();
    data.CurrentPicURL = $('.picture').val();
    //data.CurrentPicURL = $('.picture')[0].files;

    if (data.UserName && data.UPassword && data.OfficialEmailAddress && data.Departments && data.Designation && data.Role && data.IsAdmin && data.IsPermanent) {
        $.ajax({
            url: 'http://localhost:1089/api/Employee/EmpOfficialDetails',
            type: "POST",
            dataType: 'json',
            contentType: "application/json",
            data: JSON.stringify(data),
            enctype: 'multipart/form-data',
            beforeSend: function () {
                $("#dvRoomsLoader").show();
            },
            complete: function () {
                $("#dvRoomsLoader").hide();
            },
            success: function (data) {
                var ID = parseInt(data);
                if (ID > 0) {
                    //var id = data;
                    $(".HiddenID").val(data);
                    //var id = $(".HiddenID").val();
                    $('#official').css('display', 'block');
                    $('#official').html("Employees Official details added successfully...!");
                    $('#official').fadeOut(25000);
                    $("#dvRoomsLoader").show();

                    $('.empOfficialDetails').html("Update &nbsp; <i class='fa fa-angle-right rotate-icon'></i>");
                }
                else {
                    $('#official').find("alert alert-success").addClass("alert alert-danger").remove("alert alert-success");
                }
            },
            error: function (ex) {
                alert("There was an error while submitting employee data");
                alert('Error' + ex.responseXML);
                alert('Error' + ex.responseText);
                alert('Error' + ex.responseJSON);
                alert('Error' + ex.readyState);
                alert('Error' + ex.statusText);
            }
        });
        
    }
    return false;

});

我的控制器代码:

public int Emp_OfficialDetails(Employee emp)
    {
        //SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["AmanraHRMS"].ConnectionString);
        var con = DB.getDatabaseConnection();
        SqlCommand com = new SqlCommand("InsEmpOfficialDetails", con);
        com.CommandType = CommandType.StoredProcedure;

        #region Employee Official Details Insert Code block

        com.Parameters.AddWithValue("@UserName", emp.UserName);
        com.Parameters.AddWithValue("@pass", emp.UPassword);
        com.Parameters.AddWithValue("@OfficialEmailAddress", emp.OfficialEmailAddress);
        com.Parameters.AddWithValue("@Department", emp.Departments);
        com.Parameters.AddWithValue("@Role", emp.Role);
        com.Parameters.AddWithValue("@IsAdmin", Convert.ToBoolean(emp.IsAdmin));
        com.Parameters.AddWithValue("@Designation", emp.Designation);
        com.Parameters.AddWithValue("@ReportToID", emp.ReportToID);
        com.Parameters.AddWithValue("@ReportTo", emp.ReportTo);
        com.Parameters.AddWithValue("@JoiningDate", Convert.ToDateTime(emp.JoiningDate));
        com.Parameters.AddWithValue("@IsPermanent", Convert.ToBoolean(emp.IsPermanent));
        com.Parameters.AddWithValue("@DateofPermanancy", Convert.ToDateTime(emp.DateofPermanancy));
        com.Parameters.AddWithValue("@IsActive", Convert.ToBoolean(emp.IsActive));
        com.Parameters.AddWithValue("@HiredbyReference", Convert.ToBoolean(emp.HiredbyReference));
        com.Parameters.AddWithValue("@HiredbyReferenceName", emp.HiredbyReferenceName);
        com.Parameters.AddWithValue("@BasicSalary", emp.BasicSalary);
        com.Parameters.AddWithValue("@CurrentPicURL", emp.CurrentPicURL);

        #endregion
        //var file = emp.CurrentPicURL;

        //EmployeeImage(file);

        var ID = com.ExecuteScalar();
        com.Clone();
        return Convert.ToInt32(ID);
    }

    //Ajax call hit this method from AddEmployee page
    [Route("api/Employee/EmpOfficialDetails")]
    [HttpPost]
    public int? EmpOfficialDetails(Employee emp)
    {
        IHttpActionResult ret;
        try
        {
            var id = Emp_OfficialDetails(emp);
            return id;
        }
        catch (Exception ex)
        {
            ret = InternalServerError(ex);
        }
        return null;
    }

修复您的隐藏字段

<input type="hidden" asp-for ="EmpID"  id="empId" class="HiddenID" value="@Model.EmpID />

修复您的存储过程。 for exist 就足够了 EmpID,太多的参数会给出错误的结果

BEGIN
    IF EXISTS (SELECT 1 FROM Employee 
               WHERE EmpID = @EmpID)
 BEGIN
        UPDATE Employee
        SET UserName = @UserName,
         .....

最重要的是将 EmpId 添加到 ajax

  var data = new Object();
    data.EmpID = $('#empId').val();

和动作命令

 com.Parameters.AddWithValue("@EmpID", emp.EmpID);