0

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
13
  • Please edit the question to share the code for your API /api/CountryToState/FillState Commented Jun 12, 2019 at 18:42
  • @PriyankPanchal Done. Can you please help me with this Commented Jun 12, 2019 at 18:44
  • We will need one more thing, please add CountryToState model's properties. Does it contain a property named StateFullName? Commented Jun 12, 2019 at 18:45
  • @PriyankPanchal It does Commented Jun 12, 2019 at 18:48
  • 1
    Try doing console.log(states) in your ajax success callback. What does it show? You can see the console in your browser's devtools. Usually F12 on chrome. Commented Jun 12, 2019 at 18:59

1 Answer 1

2

I Reviewed your code and I think the error originates from ajax success function

$.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));
        });
    }
});

In the code above I think that state parameter in success callback has such a structure:

{
  ContentEncoding: ...
  ContentEncoding: ...
  ContentType: ...
  Data: (36) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, 
             {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, 
             {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
  JsonRequestBehavior: ...
  MaxJsonLength: ...
  RecursionLimit: ...
}

so you need to make a loop in states.Data instead of states :

$.each(states.Data, function (i, statetest) {
            $("#profileState").append(
                $('<option></option>').val(statetest.StateFullName).html(statetest.StateFullName));
        });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.