I am still very new to the whole ASP.NET MVC / AJAX / jQuery thing. I am trying to populate a couple of text boxes on my webpage based on a selection in a drop down list. However, based on my current code, I do not seem to be able to populate those text boxes with data. My initial suspect is that the 'change' event is not being triggered. Any advice is appreciated.
I am using the MVC Scaffolding to generate the corresponding Controllers and Views. I have added an extra function to return a JSON object to be used to populate the text boxes and I am pretty sure the return is correct as I do see the JSON data if I enter the request manually.
Create.cshtml - Drop down list, textbox and script in question.
... Some html codes ...
<div class="form-group">
<label class="control-label col-md-2" for="OneTimeFee">One Time Fee</label>
<div class="col-md-10">
@Html.DropDownList("OneTimeFee", null, htmlAttributes: new { @class = "form-control" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Amount, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Amount, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Amount, "", new { @class = "text-danger" })
</div>
</div>
... Some other html codes ...
<script type="text/javascript">
$('#OneTimeFee').change(function () {
$.ajax({
type: 'GET',
url: '@Url.Action("GetOneTimeFee", "FeeHistory")',
data: { onetimefeeid: $('#OneTimeFee').val() },
dataType: "json",
success: function (data) {
$('#Amount').val(data.Amount);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
$('#Amount').val('');
}
});
})
</script>
FeeHistory.cs
public async Task<ActionResult> GetOneTimeFee(String onetimefeeid)
{
Int32 id = Convert.ToInt32(onetimefeeid);
one_time_fees one_Time_Fees = await db.one_time_fees.FindAsync(id);
if(one_Time_Fees == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
return Json(one_Time_Fees, JsonRequestBehavior.AllowGet);
}
I was expecting to see the Amount textbox to be the value from the database via the JSON object. However, I do not see any changes to that textbox.
If I use Firefox to Inspect Element, the only error I get is that Reference Error: $ is not defined
.