Check duplicate before inserting to Database using jQuery AJAX with ASP.Net Core MVC

trisetia302
 
on Aug 18, 2021 05:58 AM
3034 Views

Hi Guys,

I trying to Check Availability Data before save to avoid duplicate data but the problem is I do Check and save in 1 button.

I want is every time Button save clicked will check availability the data, when data availability it will save but if data duplicate it will show the message and then the save function will not running. I put that 2 function at 1 button. How to make the logic. Any help could be apriciate.

The button

<button type="button" onclick="return Avoid2xSimpenData();" id="Btn_SaveDataPinjaman" class="btn btn-success btn-sm"><i class="fa fa-save"> Save Data Pinjaman</i></button>

Function Check Availability Data

<script type="text/javascript">
    function Avoid2xSimpenData() {
        $.ajax({
            type: "GET",
            url: "/Pinjaman/Avoid2xInputData",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: { Kode_Pinjam: $('#Kode_Pinjam').val() },
            success: OnSuccess,
            failure: function (response) {
                alert(response);
            }
        });
    }
    //function OnSuccess
    function OnSuccess(response) {
        var msg = $("#lblStatus");
        switch (response) {
            case "true":
                msg.show();
                msg.css("color", "red");
                msg.html("Data sudah disimpan sebelumnya.\n Kode Pinjaman tidak boleh sama untuk disimpan 2x !!!");
                break;
            case "false":
                msg.show();
                msg.css("color", "green");
                msg.html("Data Ok");
                break;
        }
    }
</script>

Function For Save Data

<script type="text/javascript">
    $(document).ready(function () {
        $("#Btn_SaveDataPinjaman").on("click", function () {
            var ValidasiData = validatePinjaman();
            if (ValidasiData == false) {
                return false;
            }
            $("#lblStatus").val("");
            var ObjectPinjaman = {
                Kode_Pinjam: $("#Kode_Pinjam").val(),
                Tanggal_Pinjam: $("#Tanggal_Pinjam").val(),
                Tanggal_Kembali: $("#Tanggal_Kembali").val(),
                Kode_Anggota: $("#Kode_Anggota").val(),
                Kode_Petugas: $("#Kode_Petugas").val()
            };
            $.ajax({
                url: "/Pinjaman/SaveDataPinjaman",
                data: JSON.stringify(ObjectPinjaman),
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (result) {
                    window.alert("Data berhasil disimpan..");
                    $("#HideDetailPinjamanBuku").show();
                },
                error: function (errormessage) {
                    window.alert(errormessage.responseText);
                }
            });
            return false;
        });
    });
</script>

All code above is working properly in 2 button but I want make it in 1 button.

Download FREE API for Word, Excel and PDF in ASP.Net: Download
trisetia302
 
on Aug 18, 2021 08:44 AM
on Aug 18, 2021 08:50 AM

@dharmendr

Thaks so much for the help sir.

Problem Solved Sir,

My idea is handle the logical in frondend and then still make 2 action method in controller.cs after that catch that 2 action method using ajax.

The Ajax

<script type="text/javascript" lang="javascript">
    $(document).ready(function () {
        $("#Btn_SaveDataPinjaman").on("click", function () {
            var ValidasiData = validatePinjaman();
            if (ValidasiData == false) {
                return false;
            }
            $.ajax({
                type: "GET",
                url: "/Pinjaman/Avoid2xInputData",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: { Kode_Pinjam: $('#Kode_Pinjam').val() },
                success: function (response) {
                    switch (response) {
                        case "true":
                            window.alert("Data sudah disimpan sebelumnya.\n Kode Pinjaman tidak boleh sama untuk disimpan 2x !!!");
                            break;
                        case "false":
                            var ObjectPinjaman = {
                                Kode_Pinjam: $("#Kode_Pinjam").val(),
                                Tanggal_Pinjam: $("#Tanggal_Pinjam").val(),
                                Tanggal_Kembali: $("#Tanggal_Kembali").val(),
                                Kode_Anggota: $("#Kode_Anggota").val(),
                                Kode_Petugas: $("#Kode_Petugas").val()
                            };
                            $.ajax({
                                url: "/Pinjaman/SaveDataPinjaman",
                                data: JSON.stringify(ObjectPinjaman),
                                type: "POST",
                                contentType: "application/json; charset=utf-8",
                                dataType: "json",
                                success: function (result) {
                                    window.alert("Data berhasil disimpan..");
                                    $("#HideDetailPinjamanBuku").show();
                                },
                                error: function (errormessage) {
                                    window.alert(errormessage.responseText);
                                }
                            });
                            return false;
                            break;
                    }
                },
            });
        });
    });
</script>

 Controller.cs

        [HttpPost]
        public JsonResult SaveDataPinjaman([FromBody] PinjamanModel _PinjamanModel)
        {
            int i = 0;
            using (SqlConnection con = new SqlConnection(this._configuration.GetConnectionString("db_perpustakaan")))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    con.Open();
                    cmd.Connection = con;
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = "Insert Into Peminjaman (Kode_Pinjam,Tanggal_Pinjam,Tanggal_Kembali,Kode_Petugas,Kode_Anggota) Values (@Kode_Pinjam,@Tanggal_Pinjam,@Tanggal_Kembali,@Kode_Petugas,@Kode_Anggota)";
                    cmd.Parameters.AddWithValue("@Kode_Pinjam", _PinjamanModel.Kode_Pinjam);
                    cmd.Parameters.AddWithValue("@Tanggal_Pinjam", _PinjamanModel.Tanggal_Pinjam);
                    cmd.Parameters.AddWithValue("@Tanggal_Kembali", _PinjamanModel.Tanggal_Kembali);
                    cmd.Parameters.AddWithValue("@Kode_Petugas", _PinjamanModel.Kode_Petugas);
                    cmd.Parameters.AddWithValue("@Kode_Anggota", _PinjamanModel.Kode_Anggota);
                    i = cmd.ExecuteNonQuery();
                }
            }

            return Json(i);
        }

        [HttpGet]
        public JsonResult Avoid2xInputData(string Kode_Pinjam)
        {
            string retval = "";
            using (SqlConnection con = new SqlConnection(this._configuration.GetConnectionString("db_perpustakaan")))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    con.Open();
                    cmd.Connection = con;
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = "Select Kode_Pinjam From Peminjaman Where Kode_Pinjam=@Kode_Pinjam";
                    cmd.Parameters.AddWithValue("@Kode_Pinjam", Kode_Pinjam);
                    using (SqlDataReader dr = cmd.ExecuteReader())
                        if (dr.HasRows)
                        {
                            retval = "true";
                        }
                        else
                        {
                            retval = "false";
                        }
                }
            }

            return Json(retval);
        }