I want to search the database using the dropdownlist selected value as my search key using JsonResult in entity framework core when selecting dropdownlist item instead to display the correct search result in the input box but displayed [object Object]
. I need help correcting my codes were made some mistakes. See my View, JsonResult and Jquery.
In some scenarios my table name Student with three columns
ID
StudentName
Amount
Dropdownlist display StudentName and the moment the select name of the student needs to show the amount for the student already selected in the inputbox but I have tried an error occurred display [object Object]
in the inputbox.
View
<div >
<label asp-for="Id" ></label>
<select id="studentname" asp-for="Id" asp-items="Model.Students" >
<option value="">--Please Select--</option>
</select>
<span asp-validation-for="Id" ></span>
</div>
<div >
<label asp-for="StudentAmt" ></label>
<input id="amount" asp-for="StudentAmt" />
<span asp-validation-for="StudentAmt" ></span>
</div>
JsonResult
[HttpPost]
public JsonResult StudentAmt(int id)
{
var query = _context.Student.Where(p => p.ID == id)
.Select(p => new
{
p.Amount,
});
return Json(query);
}
JQuery
<script>
$(function () {
$("#studentname").change(function () {
var struId = $(this).find("option:selected").val();
if (struId != "") {
$.ajax({
type: "POST",
url: "/Biodata/StudentAmt?id=" struId,
contentType: "application/json; charset=utf-8",
success: function (response) {
if (response != "") {
$('#amount).val(response);
} else {
$('#amount).val('');
}
}
});
} else {
$('#amount).val('');
}
});
});
</script>
CodePudding user response:
You are returning the object [object Object]
correctly from the ajax call. Try to change the code that is returning the object with the property like the following:
if (response != "") {
console.log(response);
$('#amount').val(response.amount);
}
Notice that I added the amount
property to the response object.
CodePudding user response:
Change your Backend code like:
[HttpPost]
public JsonResult StudentAmt(int id)
{
var query = _dbcontext.students.Where(p => p.Id == id).FirstOrDefault();
return Json(query);
}
Then in your ajax:
if (response != "") {
$('#amount').val(response.amount);
}
Demo:
BTW: In my opinion, You don't need to select item and send id to backend then get value and back to frontend. When you set Dropdownlist, You can set studentName as text and amount as value, When select a item, you can directly fill the value of dropdownlist into inputbox by Javascript.