Hi Guys,
I'm trying to retrieve data from database to textbox based user typed value.
I want is when user typed Kode_Petugas it will retrieve data Nama from database on textbox.
I'm using Ajax to post the value to textbox but unfortunately the code not working well.
Please help me. Any help could be appriciate
PinjamanController.cs
//retrieve data from database
[HttpPost]
public IActionResult SearchNamaPetugas(string Kode_Petugas)
{
List<PetugasModel> _ListPetugas = new List<PetugasModel>();
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 Nama From Petugas Where Kode_Petugas =@Kode_Petugas";
cmd.Parameters.AddWithValue("@Kode_Petugas", Kode_Petugas);
using(SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
_ListPetugas.Add(new PetugasModel
{
Nama = rdr["Nama"].ToString()
});
}
}
}
}
return View(_ListPetugas);
}
Create.cshtml
<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" id="txtKodePetugas" class="form-control" placeholder="Enter Kode Petugas"/>
<div class="input-group-append">
<button type="submit" id="CekNamaPetugas" class="btn btn-warning" onclick="return CariNamaPetugas(this);">Cari Kode Petugas</button>
</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" id="txtNamaPetugas" class="form-control" placeholder="Enter Nama Petugas" readonly="readonly" />
<span asp-validation-for="Nama_Petugas" class="text-danger"></span>
</div>
</div>
<script type="text/javascript" lang="javascript">
function CariNamaPetugas() {
$("#CekNamaPetugas").click(function () {
$.ajax({
url: "@Url.Action("SearchNamaPetugas", "Pinjaman")",
type:"POST",
data: { Kode_Petugas: $("#txtKodePetugas").val() },
success: function (data) {
$("#txtNamaPetugas").html(data);
}
});
});
}
</script>