[Solved] jQuery Ajax Success return [object Object] in ASP.Net Core MVC

trisetia302
 
on Aug 05, 2021 12:11 AM
1904 Views

Hi Guys,

Populate data to textbox return as object object .NET core MVC

I'm trying to Populate Data from database using Ajax but I'm getting the error.

How to solve this. Any help could be apriciate.

Create.cshtml

<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">Data Buku</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" required /></td>
                        <td>
                            <input asp-for="Penulis" class="form-control" placeholder="Enter Penulis" id="txtPenulis" name="Penulis" readonly="readonly" required /></td>
                        <td>
                            <input asp-for="Penerbit" class="form-control" placeholder="Enter Penerbit" id="txtPenerbit" name="Penerbit" readonly="readonly" required /></td>
                        <td>
                            <button type="submit" id="Btn_Search_Kode_Buku" class=" btn btn-warning btn-sm" value="">class="fa fa-search"></button></td>
                        <td>
                            <button type="submit" id="Btn_Add_Search_Kode_Buku" class=" btn btn-success btn-sm" value="">^__i class="fa fa-plus"> Add</button></td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script type="text/javascript" lang="javascript">
    $(document).ready(function () {
        $("#Btn_Search_Kode_Buku").click(function () {
            $.ajax({
                url: "@Url.Action("RetriveDataBuku", "Pinjaman")",
                type: "POST",
                data: { Kode_Buku: $("#txt_Search_Kode_Buku").val() },
                success: function (data) {
                    if (data != null) {
                        $("#txtJudul").val(data);
                        $("#txtPenulis").val(data);
                        $("#txtPenerbit").val(data);
                    }
                    else {
                        alert("Something went wrong");
                    }
                }
            });
        });
    });
</script>

Controller.cs

[HttpPost]
public List<BukuModel> RetriveDataBuku(string Kode_Buku)
{
    List<BukuModel> ListBuku = new List<BukuModel>();
    DataSet dataSetListBuku = new DataSet();
    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 Judul, Penulis, Penerbit From Buku Where Kode_Buku =@Kode_Buku";
            cmd.Parameters.AddWithValue("@Kode_Buku", Kode_Buku);
            using (SqlDataAdapter _SqlDataAdapter = new SqlDataAdapter(cmd))
            {
                _SqlDataAdapter.Fill(dataSetListBuku);
            }
            ListBuku.Add(new BukuModel
            {
                Judul = dataSetListBuku.Tables[0].Rows[0]["Judul"].ToString(),
                Penulis = dataSetListBuku.Tables[0].Rows[0]["Penulis"].ToString(),
                Penerbit = dataSetListBuku.Tables[0].Rows[0]["Penerbit"].ToString()
            });
            return ListBuku;
        }

    }
}

BukuModel.cs

[Table("Buku")]
public class BukuModel
{
    [Key]
    [Display(Name = "Kode Buku")]
    [Required(ErrorMessage = "Kode Buku tidak boleh kosong")]
    public string Kode_Buku { get; set; }

    [Display(Name = "Judul Buku")]
    [Required(ErrorMessage = "Judul Buku tidak boleh kosong")]
    public string Judul { get; set; }

    [Display(Name = "Penulis Buku")]
    [Required(ErrorMessage = "Penulis Buku tidak boleh kosong")]
    public string Penulis { get; set; }

    [Display(Name = "Penerbit Buku")]
    [Required(ErrorMessage = "Penerbit Buku tidak boleh kosong")]
    public string Penerbit { get; set; }

    [Display(Name = "Tahun Terbit Buku")]
    [Required(ErrorMessage = "Tahun Terbit Buku tidak boleh kosong")]
    public string Tahun_Terbit { get; set; }

    [Display(Name = "ISBN Buku")]
    [Required(ErrorMessage = "ISBN Buku tidak boleh kosong")]
    public string ISBN { get; set; }

    [Display(Name = "Nama Rak Buku")]
    [Required(ErrorMessage = "Nama Rak Buku tidak boleh kosong")]
    public string Nama_Rak { get; set; }

    [Display(Name = "Kategori Buku")]
    [Required(ErrorMessage = "Kategori Buku tidak boleh kosong")]
    public string Nama_Kategori { get; set; }
}

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Aug 05, 2021 02:03 AM
on Aug 06, 2021 01:55 AM

Hi trisetia302,

The default Camel Case JSON property names tend to break the Client Side JavaScript and hence in order to remove it, the default JSON Serialization needs to be replaced with Newtonsoft.Json Serialization in ASP.Net Core.

You need to Configuring the JSON Serializer setting in Startup.cs file.

Refer below article for more details.

ASP.Net Core: Changing the default Camel Case JSON Output

Refer the modified code.

Model

[Table("Buku")]
public class BukuModel
{
    [Key]
    [Display(Name = "Kode Buku")]
    [Required(ErrorMessage = "Kode Buku tidak boleh kosong")]
    public string Kode_Buku { get; set; }

    [Display(Name = "Judul Buku")]
    [Required(ErrorMessage = "Judul Buku tidak boleh kosong")]
    public string Judul { get; set; }

    [Display(Name = "Penulis Buku")]
    [Required(ErrorMessage = "Penulis Buku tidak boleh kosong")]
    public string Penulis { get; set; }

    [Display(Name = "Penerbit Buku")]
    [Required(ErrorMessage = "Penerbit Buku tidak boleh kosong")]
    public string Penerbit { get; set; }

    [Display(Name = "Tahun Terbit Buku")]
    [Required(ErrorMessage = "Tahun Terbit Buku tidak boleh kosong")]
    public string Tahun_Terbit { get; set; }

    [Display(Name = "ISBN Buku")]
    [Required(ErrorMessage = "ISBN Buku tidak boleh kosong")]
    public string ISBN { get; set; }

    [Display(Name = "Nama Rak Buku")]
    [Required(ErrorMessage = "Nama Rak Buku tidak boleh kosong")]
    public string Nama_Rak { get; set; }

    [Display(Name = "Kategori Buku")]
    [Required(ErrorMessage = "Kategori Buku tidak boleh kosong")]
    public string Nama_Kategori { get; set; }
}

Controller

public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public BukuModel RetriveDataBuku(string Kode_Buku)
    {
        // get data from database.
        BukuModel Buku = new BukuModel();
        Buku.Kode_Buku = "BOOK000002";
        Buku.Judul = "Misteri Hutan Rimba 2";
        Buku.Penulis = "Ansi M C";
        Buku.Penerbit = "Andi S";

        return Buku;
    }
}

View

@model JsonResult.Models.BukuModel
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.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_Search_Kode_Buku").click(function () {
            $.ajax({
                url: "@Url.Action("RetriveDataBuku", "Home")",
                type: "POST",
                data: { Kode_Buku: $("#txt_Search_Kode_Buku").val() },
                success: function (data) {
                    if (data != null) {
                        $("#txtJudul").val(data.Judul);
                        $("#txtPenulis").val(data.Penulis);
                        $("#txtPenerbit").val(data.Penerbit);
                    }
                    else {
                        alert("Something went wrong");
                    }
                }
            });
        });
    });
    </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">Data Buku</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" required />
                            </td>
                            <td>
                                <input asp-for="Penulis" class="form-control" placeholder="Enter Penulis" id="txtPenulis" name="Penulis" readonly="readonly" required />
                            </td>
                            <td>
                                <input asp-for="Penerbit" class="form-control" placeholder="Enter Penerbit" id="txtPenerbit" name="Penerbit" readonly="readonly" required />
                            </td>
                            <td>
                                <button type="submit" id="Btn_Search_Kode_Buku" class=" btn btn-warning btn-sm" value=""><i class="fa fa-search"> Search</i></button>
                            </td>
                            <td>
                                <button type="submit" id="Btn_Add_Search_Kode_Buku" class=" btn btn-success btn-sm" value=""><i class="fa fa-plus"> Add</i></button>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</body>
</html>

Screenshot

trisetia302
 
on Aug 06, 2021 08:33 AM

@dharmendr

Alhamdulilah

Problem Solved sir, https://pasteboard.co/KeDS71x.jpg

Thanks so much for the help.

I use this bellow sir because I use .Net Core Mvc 5.0

Startup.cs

using Newtonsoft.Json.Serialization;

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();
    services.AddControllers().AddJsonOptions(jsonOptions =>
    {
        jsonOptions.JsonSerializerOptions.PropertyNamingPolicy = null;
    });
}