[Solved] ASP.Net Core MVC Error: 500 Internal Server Error when save data to database using AJAX

trisetia302
 
on Aug 08, 2021 11:13 PM
1295 Views

Hi Guys,

500 Internal Server Error when save data to database via ajax in .Net Core Mvc

I'm trying to save data using ajax. In this case I'm not use the model for save data.

is posible to save data using "Request.Form["thefield"].ToString())" because I will save data from 2 model I think this can be solve using ajax.

Any help could be apriciate.

Create.cshtml

@using www.si.perpustakaan.Models
@model PinjamanModel
@{
    ViewData["Title"] = "Create";
    Layout = "~/Views/Shared/AdminDashboard/_Layout.cshtml";
}

<link href="~/lib/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
<script type="text/javascript" src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/assets/plugins/jquery-ui/jquery-ui.js"></script>
<link href="~/assets/plugins/jquery-ui/jquery-ui.css" rel="stylesheet" />
<script src="~/assets/plugins/sweetalert2/sweetalert2.js"></script>
<link href="~/assets/plugins/sweetalert2/sweetalert2.css" rel="stylesheet" />
<div class="tab-content">
    <div class="tab-pane tabs-animation fade show active" id="tab-content-0" role="tabpanel">
        <div class="row">
            <div class="col-md-12">
                <div class="main-card mb-3 card">
                    <div class="card-body">
                        <!-- Modal Header -->
                        <div class="modal-header bg bg-success">
                            <div align="center">
                                <h4 class="modal-title"><b>Add Data Pinjaman</b></h4>
                            </div>
                        </div>
                        <hr />
                        <form asp-action="" asp-controller="" method="post">
                            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="position-relative form-group">
                                        <label asp-for="Kode_Pinjam" class="control-label"></label>
                                        <input asp-for="Kode_Pinjam" id="txtKode_Pinjam" name="Kode_Pinjam" class="form-control" readonly="readonly" />
                                        <span asp-validation-for="Kode_Pinjam" class="text-danger"></span>
                                    </div>
                                </div>

                                <div class="col-md-6">
                                    <div class="position-relative form-group">
                                        <label asp-for="Tanggal_Pinjam" class="control-label"></label>
                                        <input asp-for="Tanggal_Pinjam" class="form-control" placeholder="Enter Tanggal Pinjam Buku" />
                                        <span asp-validation-for="Tanggal_Pinjam" class="text-danger"></span>
                                    </div>
                                </div>

                                <div class="col-md-6">
                                    <div class="position-relative form-group">
                                        <label asp-for="Tanggal_Kembali" class="control-label"></label>
                                        <input asp-for="Tanggal_Kembali" class="form-control" placeholder="Enter Tanggal Kembali Buku" />
                                        <span asp-validation-for="Tanggal_Kembali" class="text-danger"></span>
                                    </div>
                                </div>

                                <div class="col-md-6">
                                    <div class="position-relative form-group">
                                        <label asp-for="Kode_Anggota" class="control-label"></label>
                                        <div class="input-group">
                                            <input asp-for="Kode_Anggota" class="form-control" id="txtKodeAnggota" placeholder="Enter Kode Anggota" required />
                                            <div class="input-group-append">
                                                <input type="submit" id="CekNamaAnggota" value="Cari Kode Anggota" class="btn btn-warning" />
                                            </div>
                                        </div>
                                        <span asp-validation-for="Kode_Anggota" class="text-danger"></span>
                                    </div>
                                </div>

                                <div class="col-md-6">
                                    <div class="position-relative form-group">
                                        <label asp-for="Nama_Anggota" class="control-label"></label>
                                        <input asp-for="Nama_Anggota" class="form-control" id="txtNamaAnggota" placeholder="Enter Nama Anggota" readonly="readonly" />
                                    </div>
                                    <span asp-validation-for="Nama_Anggota" class="text-danger"></span>
                                </div>

                                <div class="col-md-6">
                                    <div class="position-relative form-group">
                                        <label asp-for="Kode_Petugas" class="control-label"></label>
                                        <div class="input-group">
                                            <input asp-for="Kode_Petugas" class="form-control" id="txtKodePetugas" placeholder="Enter Kode Petugas" required />
                                            <div class="input-group-append">
                                                <input type="submit" id="CekNamaPetugas" value="Cari Kode Petugas" class="btn btn-warning" />
                                            </div>
                                        </div>
                                        <span asp-validation-for="Kode_Petugas" class="text-danger"></span>
                                    </div>
                                </div>

                                <div class="col-md-6">
                                    <div class="position-relative form-group">
                                        <label asp-for="Nama_Petugas" class="control-label"></label>
                                        <input asp-for="Nama_Petugas" class="form-control" id="txtNamaPetugas" placeholder="Enter Nama Petugas" readonly="readonly" />
                                    </div>
                                    <span asp-validation-for="Nama_Petugas" class="text-danger"></span>
                                </div>

                                @*Data Buku*@
                                <div class="col-md-12">
                                    <div class="main-card mb-3 card">
                                        <div class="card-body">
                                            <!-- Modal Header -->
                                            <div class="modal-header bg bg-primary">
                                                <div align="center">
                                                    <h4 class="modal-title"><b>Data Buku</b></h4>
                                                </div>
                                            </div>
                                            <hr />

                                            <table>
                                                <thead>
                                                    <tr>
                                                        <th>Kode Buku</th>
                                                        <th>Judul</th>
                                                        <th>Penulis</th>
                                                        <th>Penerbit</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <tr>
                                                        <td><input asp-for="Kode_Buku" class="form-control" placeholder="Enter Kode Buku" id="txt_Search_Kode_Buku" name="Kode_Buku" required /></td>
                                                        <td><input asp-for="Judul" class="form-control" placeholder="Enter Judul Buku" id="txtJudul" name="Judul" readonly="readonly" /></td>
                                                        <td><input asp-for="Penulis" class="form-control" placeholder="Enter Penulis" id="txtPenulis" name="Penulis" readonly="readonly" /></td>
                                                        <td><input asp-for="Penerbit" class="form-control" placeholder="Enter Penerbit" id="txtPenerbit" name="Penerbit" readonly="readonly" /></td>
                                                        <td><button type="submit" id="Btn_Search_Kode_Buku" class=" btn btn-warning btn-sm"><i class="fa fa-search"> Cari</i></button></td>
                                                        <td><button type="submit" id="Btn_Add_Search_Kode_Buku" class=" btn btn-success btn-sm"><i class="fa fa-plus"> Add</i></button></td>
                                                    </tr>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>

                                <div class="col-md-12">
                                    <div class="form-group">
                                        <div align="center">
                                            <input type="submit" value="Save Data Pinjaman" class="btn btn-success" />
                                        </div>
                                    </div>
                                    <div>
                                        <a asp-action="Index"><i class="fa fa-arrow-alt-circle-left"> Back to List</i></a>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript" lang="javascript">
    $(document).ready(function () {
        $('#Btn_Add_Search_Kode_Buku').on('click', function () {
            var BukuObj = {
                Kode_Pinjam: $('#txtKode_Pinjam').val(),
                Kode_Buku: $('#txt_Search_Kode_Buku').val(),
                Judul: $('#txtJudul').val(),
                Penulis: $('#txtPenulis').val(),
                Penerbit: $('#txtPenerbit').val()
            }
             $.ajax({
                url: "@Url.Action("SaveData_Search_Buku", "Pinjaman")",
                type: "POST",
                contentType: "application/json;charset=UTF-8",
                dataType: "json",
                data: JSON.stringify(BukuObj),
                success: function () {
                    window.alert('Data berhasil disimpan...');
                 }
             });
        })
    });
</script>
<script type="text/javascript" lang="javascript">
    $(document).ready(function () {
        $('#Btn_Search_Kode_Buku').on("click", function () {
             $.ajax({
                url: "@Url.Action("Get_DataBukuByID", "Pinjaman")",
                type: "GET",
                contentType: "application/json;charset=UTF-8",
                dataType: "json",
                data: { Kode_Buku: $('#txt_Search_Kode_Buku').val() },
                 success: function (data) {
                     if (data !="") {
                         $('#txtJudul').val(data.Judul);
                         $('#txtPenulis').val(data.Penulis);
                         $('#txtPenerbit').val(data.Penerbit);
                     }
                     else {
                         window.alert(' error : ' + data.message);
                     }
                 }
             });
        });
        //return false;
    });
</script>
<script type="text/javascript" lang="javascript">
    $("[id*=Tanggal_Pinjam]").attr("ReadOnly", true)
    $("[id*=Tanggal_Pinjam]").datepicker(
        {
            dateFormat: "yy/mm/dd"
        });

    $("[id*=Tanggal_Kembali]").attr("ReadOnly", true)
    $("[id*=Tanggal_Kembali]").datepicker(
        {
            dateFormat: "yy/mm/dd"
        });
</script>
@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

Controller.cs

//Method for Save data to database DetailPinjamanBuku 
[HttpPost]
public IActionResult SaveData_Search_Buku()
{
    int i;
    using (SqlConnection con = new SqlConnection(this._configuration.GetConnectionString("db_perpustakaan")))
    {
        using (SqlCommand com = new SqlCommand())
        {
            con.Open();
            com.CommandType = CommandType.Text;
            com.CommandText = "Insert Into Detail_Pinjaman (Kode_Pinjam, Kode_Buku, Judul, Penulis, Penerbit) Values (@Kode_Pinjam, @Kode_Buku, @Judul, @Penulis, @Penerbit)";
            com.Parameters.AddWithValue("@Kode_Pinjam", Request.Form["Kode_Pinjam"].ToString());
            com.Parameters.AddWithValue("@Kode_Buku", Request.Form["Kode_Buku"].ToString());
            com.Parameters.AddWithValue("@Judul", Request.Form["Judul"].ToString());
            com.Parameters.AddWithValue("@Penulis", Request.Form["Penulis"].ToString());
            com.Parameters.AddWithValue("@Penerbit", Request.Form["Penerbit"].ToString());
            i = com.ExecuteNonQuery();
        }
    }
    return Json(i);
}

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Aug 09, 2021 04:15 AM

Hi trisetia302,

You need to create a class that will hold all the field data.

Then pass that class to the ActionResult as parameter.

Refer below code.

Model

public class KodeBuku
{
    public string Kode_Pinjam { get; set; }
    public string Kode_Buku { get; set; }
    public string Judul { get; set; }
    public string Penulis { get; set; }
    public string Penerbit { get; set; }
}

Controller

public class HomeController : Controller
{
    private IConfiguration _configuration;

    public HomeController(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public IActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public IActionResult SaveData_Search_Buku([FromBody] KodeBuku kodeBuku)
    {
        int i = 0;
        using (SqlConnection con = new SqlConnection(this._configuration.GetConnectionString("db_perpustakaan")))
        {
            using (SqlCommand com = new SqlCommand())
            {
                con.Open();
                com.CommandType = CommandType.Text;
                com.CommandText = "Insert Into Detail_Pinjaman (Kode_Pinjam, Kode_Buku, Judul, Penulis, Penerbit) Values (@Kode_Pinjam, @Kode_Buku, @Judul, @Penulis, @Penerbit)";
                com.Parameters.AddWithValue("@Kode_Pinjam", kodeBuku.Kode_Pinjam);
                com.Parameters.AddWithValue("@Kode_Buku", kodeBuku.Kode_Buku);
                com.Parameters.AddWithValue("@Judul", kodeBuku.Judul);
                com.Parameters.AddWithValue("@Penulis", kodeBuku.Penulis);
                com.Parameters.AddWithValue("@Penerbit", kodeBuku.Penerbit);
                i = com.ExecuteNonQuery();
            }
        }

        return Json(i);
    }
}

View

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript" lang="javascript">
    $(document).ready(function () {
        $('#Btn_Add_Search_Kode_Buku').on('click', function () {
            var BukuObj = {
                Kode_Pinjam: $('#txtKode_Pinjam').val(),
                Kode_Buku: $('#txt_Search_Kode_Buku').val(),
                Judul: $('#txtJudul').val(),
                Penulis: $('#txtPenulis').val(),
                Penerbit: $('#txtPenerbit').val()
            }
            $.ajax({
                url: "@Url.Action("SaveData_Search_Buku", "Home")",
                type: "POST",
                contentType: "application/json;charset=UTF-8",
                dataType: "json",
                data: JSON.stringify(BukuObj),
                success: function () {
                    window.alert('Data berhasil disimpan...');
                }
            });

            return false;
        })
    });
    </script>
</head>
<body>
    <div class="col-md-12">
        <div class="main-card mb-3 card">
            <div class="card-body">
                <!-- Modal Header -->
                <div class="modal-header bg bg-primary">
                    <div align="center">
                        <h4 class="modal-title"><b>Data Buku</b></h4>
                    </div>
                </div>
                <hr />

                <table>
                    <thead>
                        <tr>
                            <th>Kode Buku</th>
                            <th>Judul</th>
                            <th>Penulis</th>
                            <th>Penerbit</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td><input class="form-control" placeholder="Enter Kode Buku" id="txt_Search_Kode_Buku" name="Kode_Buku" required /></td>
                            <td><input class="form-control" placeholder="Enter Judul Buku" id="txtJudul" name="Judul" /></td>
                            <td><input class="form-control" placeholder="Enter Penulis" id="txtPenulis" name="Penulis" /></td>
                            <td><input class="form-control" placeholder="Enter Penerbit" id="txtPenerbit" name="Penerbit" /></td>
                            <td><button type="submit" id="Btn_Search_Kode_Buku" class=" btn btn-warning btn-sm"><i class="fa fa-search"> Cari</i></button></td>
                            <td><button type="submit" id="Btn_Add_Search_Kode_Buku" class=" btn btn-success btn-sm"><i class="fa fa-plus"> Add</i></button></td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <div class="col-md-12">
        <div class="form-group">
            <div align="center">
                <input type="submit" value="Save Data Pinjaman" class="btn btn-success" />
            </div>
        </div>
        <div>
            <a asp-action="Index"><i class="fa fa-arrow-alt-circle-left"> Back to List</i></a>
        </div>
    </div>
</body>
</html>

 

trisetia302
 
on Aug 12, 2021 06:42 AM

@dharmendr

Problem Solved

Thanks so much for the help sir

you're excelent.

Controller.cs

        [HttpPost]
        public JsonResult SaveData_Search_Buku([FromBody]Detail_Pinjaman_Buku pinjaman_Buku)
        {
            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 Detail_Pinjaman (Kode_Pinjam, Kode_Buku, Judul, Penulis, Penerbit) Values (@Kode_Pinjam, @Kode_Buku, @Judul, @Penulis, @Penerbit)";

                    cmd.Parameters.AddWithValue("@Kode_Pinjam", pinjaman_Buku.Kode_Pinjam);
                    cmd.Parameters.AddWithValue("@Kode_Buku", pinjaman_Buku.Kode_Buku);
                    cmd.Parameters.AddWithValue("@Judul", pinjaman_Buku.Judul);
                    cmd.Parameters.AddWithValue("@Penulis", pinjaman_Buku.Penulis);
                    cmd.Parameters.AddWithValue("@Penerbit", pinjaman_Buku.Penerbit);

                    i = cmd.ExecuteNonQuery();
                    con.Close();
                }
            }
            return Json(i);
        }