Заполните значения параметра Dropdown из API MVC C # - PullRequest
0 голосов
/ 12 июня 2019

У меня есть API, который вызывается при изменении выпадающего значения. Он возвращает результаты JSON, и я хотел бы обновить еще один выпадающий список из этих результатов JSON, но я продолжаю получать сообщение об ошибке в моем 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-код

 [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 Модель

 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; }
}

По-прежнему выдается сообщение об ошибке. Невозможно прочитать свойство StateFullName со значением NULL. у состояний, возвращаемых в успехе, есть 36 строк с StateFullName каждой строки. Почему это ноль. Как я могу это исправить. Я хочу, чтобы значение и текст в раскрывающемся списке были StateFullName.

Я неправильно понимаю функцию .each

Console.Log (состояния) показывает следующее:

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

1 Ответ

1 голос
/ 13 июня 2019

Я проверил ваш код и думаю, что ошибка происходит из-за успешной функции ajax

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

В приведенном выше коде я думаю, что параметр state в успешном обратном вызове имеет такую ​​структуру:

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

, поэтому вам нужно сделать цикл в состояниях. Данные вместо состояний:

$.each(states.Data, function (i, statetest) {
            $("#profileState").append(
                $('<option></option>').val(statetest.StateFullName).html(statetest.StateFullName));
        });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...