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 class="form-group col-md-4">
<label asp-for="Id" class="control-label"></label>
<select id="studentname" asp-for="Id" asp-items="Model.Students" class="form-control">
<option value="">--Please Select--</option>
</select>
<span asp-validation-for="Id" class="text-danger"></span>
</div>
<div class="form-group col-md-4">
<label asp-for="StudentAmt" class="control-label"></label>
<input id="amount" asp-for="StudentAmt" class="form-control" />
<span asp-validation-for="StudentAmt" class="text-danger"></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>
2
Answers
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:Notice that I added the
amount
property to the response object.Change your Backend code like:
Then in your ajax:
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.