javascript - 从 API MVC C# 填充下拉选项值

标签 javascript c# jquery ajax asp.net-mvc

我有一个 API,当下拉值更改时会调用该 API。它返回 JSON 结果,我想更新这些 JSON 结果的另一个下拉列表,但我的 Jquery 中不断出现错误

Razor 查看页面

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

国家到国家模型

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

它一直给我一个错误,无法读取 null 的属性“StateFullName”。 success 函数返回的 states 有 36 行,每行都有 StateFullName。为什么它是空的。我怎样才能解决这个问题。我希望下拉列表中的值和文本为 StateFullName。

我没有正确理解 .each 函数

Console.Log(states) 显示以下内容:

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

最佳答案

我检查了您的代码,我认为错误源自 ajax success 函数

$.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: ...
}

所以你需要在states.Data而不是states中进行循环:

$.each(states.Data, function (i, statetest) {
            $("#profileState").append(
                $('<option></option>').val(statetest.StateFullName).html(statetest.StateFullName));
        });

关于javascript - 从 API MVC C# 填充下拉选项值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56568397/

相关文章:

javascript - 如何在 Ext.menu.Menu 的项目上禁用浏览器上下文菜单?

javascript - Bootstrap 导航栏折叠切换按钮未单击

javascript - 绑定(bind)到鼠标滚轮的平滑水平滚动

JavaScript:当我从 iframe 函数传递数组时,数组失去了他的类型!

jquery - CSS 过渡不适用于 ajax 内容

JavaScript 添加问题

c# - 将所有子节点作为 Json 返回动态对象 - 错误 : cannot use a lambda expression as an argument to a dynamically dispatched

c# - 如何从 aspx.cs 获取参数到 javascript

c# - 从 BackgroundWorker C# 调用的 CoInitialize

jquery - 使用 API 加载更多 GitHub 用户关注者