I have a API that is called when dropdown value changes. It returns JSON results and I would like to update another dropdown from those JSON results but I keep getting an error in my Jquery
Razor View Page
<div class="form-group">
@Html.LabelFor(model => model.CustomerProfile.Country, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.CustomerProfile.Country, Model.CountryList, htmlAttributes: new { @id = "profileCountry", @class = "form-control col-md-2" , @onchange = "FillState()" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.CustomerProfile.State, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.CustomerProfile.State, new SelectList(Enumerable.Empty<SelectListItem>(), "StateFullName", "StateFullName"),
"Select State",
htmlAttributes: new { @id = "profileState", @class = "form-control col-md-2" })
</div>
</div>
Jquery Script
<script>
function FillState() {
var countryParam = $('#profileCountry').val();
$.ajax({
url: '/api/CountryToState/FillState',
type: "GET",
dataType: "JSON",
data: { country: countryParam},
success: function (states) {
$("#profileState").html(""); // clear before appending new list
$.each(states, function (i, statetest) {
$("#profileState").append(
$('<option></option>').val(statetest.StateFullName).html(statetest.StateFullName));
});
}
});
}
</script>
API Code
[System.Web.Http.HttpGet]
public ActionResult FillState(string country)
{
var states = _context.CountryToState.Where(c => c.CountryName == country);
return new JsonResult()
{
Data = states,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
CountryToState Model
public class CountryToState
{
[Column("lngStateID")]
[Key]
public Int32 StateID { get; set; }
[Column("strCountry")]
public string CountryName { get; set; }
[Column("strStateFullName")]
public string StateFullName { get; set; }
}
It keeps giving me an error on Cannot read property 'StateFullName' of null. states returned in success function has 36 rows with StateFullName of every row. Why it is null. How can I fix this. I want value and text to be StateFullName in the drop down.
I do not understand the .each function properly
Console.Log(states) show the following:
ContentEncoding: null, ContentType: null, Data: Array(36), JsonRequestBehavior: 0, MaxJsonLength: null, …}
ContentEncoding: null
ContentType: null
Data: (36) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
JsonRequestBehavior: 0
MaxJsonLength: null
RecursionLimit: null
__proto__: Object
/api/CountryToState/FillStateCountryToStatemodel's properties. Does it contain a property namedStateFullName?console.log(states)in your ajaxsuccesscallback. What does it show? You can see the console in your browser's devtools. UsuallyF12on chrome.