mardi 28 septembre 2021

Update user information section by section

In my previous question I was asking about how to update a user on the spot means right after inserting the user, but now I am asking about updating the user after inserting all of the fields section by section and by section I means that in my web application I have total 7 sections and each section has its own set of input fields but all the sections holds information for a single user, all of the sections are inserted one by one against a single user ID and the updating is done by first retrieving all of the filed values from database

this is my user data retrieving function which fills up all my input field values

function getParameterByName(name, url = window.location.href) {
    name = name.replace(/[\[\]]/g, '\\$&');
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
        ids = regex.exec(url);
    if (!ids) return null;
    if (!ids[2]) return '';
    return decodeURIComponent(ids[2].replace(/\+/g, ' '));
}

$(window).on('load', function () {
    var empid = getParameterByName('id');
    if (empid != null) {
        $('HiddenID').val(empid);
        alert("Editing Employee having ID " + empid);
        $('#main-heading').html("Edit Employee");

        $('.empOfficialDetails').html("Update &nbsp; <i class='fa fa-angle-right rotate-icon'></i>");
        //$('.empOfficialDetails').prop('disabled', 'true');

        $('#collapseTwo2').show();
        $('.empPersonalDetails').html("Update &nbsp; <i class='fa fa-angle-right rotate-icon'></i>");
        //$('.empPersonalDetails').prop('disabled', 'true');

        $('#collapseThree3').show();
        $('.empExperienceDetails').html("Update &nbsp; <i class='fa fa-angle-right rotate-icon'></i>");
        //$('.empExperienceDetails').prop('disabled', 'true');

        $('#collapseFour4').show();
        $('.empEducationDetails').html("Update &nbsp; <i class='fa fa-angle-right rotate-icon'></i>");
        //$('.empEducationDetails').prop('disabled', 'true');

        $('#collapseFive5').show();
        $('.empVaccinationDetails').html("Update &nbsp; <i class='fa fa-angle-right rotate-icon'></i>");
        //$('.empVaccinationDetails').prop('disabled', 'true');

        $('#collapseSix6').show();
        $('.empBenefitDetails').html("Update &nbsp; <i class='fa fa-angle-right rotate-icon'></i>");
        //$('.empBenefitDetails').prop('disabled', 'true');

        $('#collapseSeven7').show();
        $('.empBankDetails').html("Update &nbsp; <i class='fa fa-angle-right rotate-icon'></i>")

        GetEmployee(empid);
    }
});

function GetEmployee(EmpID) {


    $.ajax({
        url: 'http://localhost:1089/api/Employee/RetrieveEmployee?id=' + EmpID,
        type: "GET",
        //data: { id: EmpID },
        dataType: 'json',
        contentType: "application/json",
        beforeSend: function () {
            $("#dvRoomsLoader").show();
        },
        complete: function () {
            $("#dvRoomsLoader").hide();
        },
        success: function (data) {
            var v = data[0];
            //$(data).each(function (i, v) {

            $('#empId').val(v.empID);
            $('#username').val(v.userName);
            $('#userpass').val(v.pass);
            $('#officialemail').val(v.officialEmailAddress);
            $('#departments :selected').val(v.department);
            $('#designation').val(v.designation);
            $('#role :selected').val(v.role);
            $('#reportToID').val(v.reportToID);
            $('#reportTo :selected').text(v.reportTo);
            $('#joindate').val(v.joiningDate);
            $('#isAdmin :selected').text(v.isAdmin);
            $('#isActive :selected').text(v.isActive);
            $('#isPermanent :selected').text(v.isPermanent);
            $('#permanantdate').val(v.dateofPermanancy);
            $('#hiredbyRef :selected').text(v.hiredbyReference);
            $('#refePersonName').val(v.hiredbyReferenceName);
            $('#basicSalary').val(v.basicSalary);
            $('#firstname').val(v.firstName);
            $('#middlename').val(v.middleName);
            $('#lastname').val(v.lastName);
            $('#age').val(v.age);
            $('#gender :selected').text(v.gender);
            $('#dateofBirth').val(v.dateOfBirth);
            $('#maritalstatus').val(v.maritalStatus);
            $('#noofchildrens').val(v.nunmberOfChildrens);
            $('#noofdependants').val(v.numberOfDependents);
            $('#mobilenumber').val(v.mobileNumber);
            $('#alternatemobile').val(v.alternateMobileNumber);
            $('#ptcl').val(v.ptclNumber);
            $('#ecPerson :selected').text(v.typeOFEmergencyContact);
            $('#ecNumber').val(v.emergencyNumber);
            $('#emailaddress').val(v.emailAddress);
            $('#cnicnumber').val(v.cnicNumber);
            $('#cnicexpdate').val(v.cnicExpDate);
            $('#ntnnumber').val(v.ntnNumber);
            $('#passpNo').val(v.passportNumber);
            $('#passpExpDate').val(v.passportExpDate);
            $('#permanentaddress').val(v.permanentAddress);
            $('#officialaddress').val(v.officialAddress);
            $('#unofficialaddress').val(v.unOfficialAddress);
            $('#country').val(v.country);
            $('#city').val(v.city);
            $('#state').val(v.state);
            $('#postalcode').val(v.postalCode);
            $('#nationality').val(v.nationality);
            $('#religion').val(v.religion);
            $('#firqa').val(v.firqa);
            $('#cast').val(v.empCast);
            $('#bloodgroup :selected').text(v.bloodGroup);
            $('#facebookurl').val(v.facebookURL);
            $('#linkedinurl').val(v.linkedInURL);
            $('#twitterurl').val(v.twitterURL);
            $('#youtubelink').val(v.youtubeChannelURL);
            $('#githuburl').val(v.gitHubURL);
            $('#portfoliourl').val(v.portfolioURL);
            $('#currentDesg').val(v.currentDesignation);
            $('#lastDesg').val(v.lastDesignation);
            $('#initialDesg').val(v.initialDesignation);
            $('#totalExp').val(v.totalExperience);
            $('#lastEmpName').val(v.lastEmployerName);
            $('#lastEmpDesg').val(v.lastEmployerDesignation);
            $('#lastEmpSal').val(v.lastEmployerGrossSalary);
            $('#institutename').val(v.institutename);
            $('#typeofdegree').val(v.typeOFDegree);
            $('#majorcourse').val(v.majorCourses);
            $('#startdate').val(v.startDate);
            $('#enddate').val(v.endDate);
            $('#isVacc :selected').text(v.isvaccinated);
            $('#noofVacc').val(v.noOfVaccination);
            $('#lastVaccDate').val(v.lastVaccinationDate);
            $('#lastVaccName').val(v.lastVaccinationName);
            $('#grossSal').val(v.grossSalary);
            $('#currSalTax').val(v.currentSalaryTax);
            $('#houseRent').val(v.houseRent);
            $('#transAll').val(v.transportAllowance);
            $('#MedicAll').val(v.medicalAllowance);
            $('#medicCardNo').val(v.medicalCardNumber);
            $('#hasLoan :selected').text(v.hasLoan);
            $('#remainingLoan').val(v.currentRemainingLoan);
            $('#currLoanBal').val(v.currentLoanBalance);
            $('#currEOBI').val(v.currentEOBI);
            $('#pvdFund').val(v.currentProvidentFund);
            $('#crSickLeaves').val(v.currentRemainingSickLeaves);
            $('#crAnnualLeaves').val(v.currentRemainingAnnualLeaves);
            $('#crCasualLeaves').val(v.currentRemainingCasualLeaves);
            $('#crUmrahLeaves').val(v.currentRemainingUmrahLeaves);
            $('#crMaternityLeaves').val(v.currentRemainingMaternityLeaves);
            $('#accountholder').val(v.accountHolderName);
            $('#bankname').val(v.bankName);
            $('#accountno').val(v.bankAccountNumber);
            $('#ibanno').val(v.ibaNnumber);
            $('#accountType').val(v.accountType);
            $('#branchlocation').val(v.branchLocation);
            $('#branchcode').val(v.branchCode);
            $('#officialaccount').val(v.isOfficial);
            //})

            alert("Data Load success");
        },
        error: function (ex) {
            alert("Data Load Fail");
            alert('Error' + ex.responseXML);
            alert('Error' + ex.responseText);
            alert('Error' + ex.responseJSON);
            alert('Error' + ex.readyState);
            alert('Error' + ex.statusText);
        }
    });
}

and this the first update function I am using to update the first section of my application;

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

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

    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),
            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;

});

the problem is that my EmpID parameter in my ajax is not picking up the id and hence it is passing as null/empty value and because my EmpID parameter is empty the ajax call doesn't get to my controller and in order to update the user my EmpID parameter need the id which I don't know why it's not picking up, although the retrieving function works smoothly, I just want know that how can I pass the retrieved ID to my EmpID parameter in order to hit my controller and successfully run my update function

here is my controller update function, but for a reminder I am mentioning again that this update function is also my insert function as well, means at the time of adding a new user it acts as insert and right after insert it act as update:

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", Crypto.HashPassword(emp.UPassword));
        com.Parameters.AddWithValue("@OfficialEmailAddress", emp.OfficialEmailAddress);
        com.Parameters.AddWithValue("@Department", emp.Departments);
        com.Parameters.AddWithValue("@Role", emp.Role);
        com.Parameters.AddWithValue("@IsAdmin", 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", emp.IsPermanent);
        com.Parameters.AddWithValue("@DateofPermanancy", Convert.ToDateTime(emp.DateofPermanancy));
        com.Parameters.AddWithValue("@IsActive", emp.IsActive);
        com.Parameters.AddWithValue("@HiredbyReference", emp.HiredbyReference);
        com.Parameters.AddWithValue("@HiredbyReferenceName", emp.HiredbyReferenceName);
        com.Parameters.AddWithValue("@BasicSalary", emp.BasicSalary);
        com.Parameters.AddWithValue("@CurrentPicURL", emp.CurrentPicURL);
        com.Parameters.AddWithValue("@EmpID", emp.EmpID);

        #endregion

        //uncomment when getting the image as file object from ajax
        //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)
    {
        var id = emp.EmpID;
        IHttpActionResult ret;
        try
        {
            id = Emp_OfficialDetails(emp);
            return id;
        }
        catch (Exception ex)
        {
            ret = InternalServerError(ex);
        }
        return null;
    }

all the help I will get on this is highly appreciated and suggestions for betterment of this code are warmly welcomed and all, all of you guys are amazing, helping each other out thank you by the I have learned a lot from all you




Aucun commentaire:

Enregistrer un commentaire