【问题标题】:drop down does not show value and text asp.net mvc下拉不显示值和文本 asp.net mvc
【发布时间】:2020-11-05 16:41:13
【问题描述】:

我有两张表States和Cities

具有两个下拉列表,当状态下拉时,选项应在城市下拉列表中提供,但不知何种文本和值不会出现

状态 ViewBag 和下拉列表

ViewBag.State = new SelectList(db.StateRepository.GetAll(), "StateId", "StateTitle");
@Html.DropDownList("States",(SelectList)ViewBag.State, "Please Select", htmlAttributes: new { @class = "form-control", id="State"})

城市下拉菜单

<select class="form-control" id="City">    </select>

控制器中的Json

  public ActionResult GetCities(int id)
  {

            var data = db.Cities.Where(d => d.StateId == id).Select(d => new { Text = d.CityTitle, Value = d.CityId });
            return Json(data, JsonRequestBehavior.AllowGet);
  }

脚本

 $("#State").change(function() {
        var loading = $('<option></option>').text("Please Wait");
        $('#City').attr("disabled", "disabled").empty().append(loading);

        $.getJSON("/GetCities/" + $("#State > option:selected").attr("value"),
            function(result) {
                $("#City").removeAttr("disabled").empty().append($("<option></option)").val("").text("Please Select"));
                    $.each(result,
                        function(item) {
                            $("#City").append($("<option></option>").val(item.value).text(item.text));
                        });
                });
  });

通过不显示值和文本,我的意思是我的桌子上有 4 个“x”州的城市, 在视图中,当我将 StateDropDown 更改为“x”状态时,它只在我的 City DropDown 列表中显示 4 个空 &lt;option&gt;&lt;/option&gt;,没有任何文本和值

伙计们,我非常感谢您的所有帮助,我是新手,我不知道问题是什么,所以请帮忙。

【问题讨论】:

    标签: c# jquery ajax asp.net-mvc dropdown


    【解决方案1】:

    编辑:我认为从控制器返回的结果是返回一个对象,如:

    [{ "Text": "..", "Value": ".." }]
    

    所以你想绑定:

    $.each(result, function(item) {
        $("#City").append($("<option></option>").val(item.Value).text(item.Text));
    });
    

    Value 和 Text 应该是大写的。

    【讨论】:

    • 在我的代码中不正确,这是因为我的最终编辑。我不知道该死的问题是什么,请再次查看代码。 tnx
    • 查看我的编辑。我认为 item.value 和 item.text 应该是 item.Value 和 item.Text
    猜你喜欢
    • 2016-09-23
    • 2021-09-18
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 2018-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多