Click here to Skip to main content
15,072,209 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi Guys,, I'm trying to Populate Data from database using Ajax but I'm getting the error as shown like this capture https://pasteboard.co/KejDiNR.jpg[^] . How to solve this. Any help could be apriciate.

What I have tried:

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; }
	}
Posted
Updated 8-Aug-21 23:21pm

There's no error in your screen-shot.

If you mean the "[object Object]" values shown in your textboxes, that's because you're setting the value to the complete list of BukuModel objects, which obviously can't be displayed in a single textbox. You need to set the value to the specific property of the first item in the returned list:
JavaScript
success: function (data) {
    if (data && data.length) {
        $("#txtJudul").val(data[0].Judul);
        $("#txtPenulis").val(data[0].Penulis);
        $("#txtPenerbit").val(data[0].Penerbit);
    }
    else {
        alert("Something went wrong");
    }
}

However, this does raise the question of why you are returning a list of results, if you're only going to be using one of them.
   
Comments
tri setia 5-Aug-21 6:46am
   
I have tried the code above sir but no data populate on the textbox, on web debugger the request passed properly but no data return to fill textbox. Maybe any another idea sir ?
Richard Deeming 5-Aug-21 6:47am
   
If no data is being returned, then your query is not returning any records.

You need to debug your code to check the parameter that's being passed, and then try to work out why the record isn't being found.

We can't do that for you.
tri setia 5-Aug-21 6:52am
   
Ok sir,, Thanks for the help, I will try to find the problem why that is happen.
Problem Solved, https://pasteboard.co/KeDS71x.jpg
.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;
    });
}


Controller.cs
[HttpGet]
        public IActionResult Get_DataBukuByID(string Kode_Buku)
        {
            BukuModel buku = new BukuModel();
            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.Trim() + "'";
                    cmd.Parameters.AddWithValue("@Kode_Buku", Kode_Buku);
                    using (SqlDataReader rdr = cmd.ExecuteReader())
                    {
                        if (rdr.Read())
                        {
                            buku.Judul = rdr["Judul"].ToString();
                            buku.Penulis = rdr["Penulis"].ToString();
                            buku.Penerbit = rdr["Penerbit"].ToString();
                        }
                        else
                        {
                            ViewBag.Message = "Kode Buku tidak ditemukan !!!";
                        }
                    }
                }
            }
            return Json(buku);
        }


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

                 }
             });
        });
    });
</script>
   
Comments
tri setia 9-Aug-21 8:39am
   
ok thanks for the advice sir,,
I will correct it.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900