【问题标题】:ASP.NET MVC Cascade ComboBoxASP.NET MVC 级联组合框
【发布时间】:2017-10-25 18:28:59
【问题描述】:

我正在尝试根据上面 ComboBox 的选择来刷新我的 ComboBox。 我有以下控制器代码:

根据第一个选择填充第二个Combobox的控制器方法代码

public JsonResult Testeeee(int id_cat )
{
    var result = new dificuldade();

    SqlCommand com;

    string str;
    SqlConnection conn = new SqlConnection(@"Server=DESKTOP-4GPISBO\SQLEXPRESS;Database=Jogo;Trusted_Connection=True;");
    conn.Open();

    str = "select tipo_dificuldade, dificuldade.id_dificuldade " +
           "from dificuldade " +
           "INNER JOIN palavra ON palavra.id_dificuldade = dificuldade.id_dificuldade " +
           "where palavra.id_cat = '" + id_cat + "'  ";

    com = new SqlCommand(str, conn);
    SqlDataReader reader = com.ExecuteReader();
    if (reader.Read())
    {
        result.TIPO_DIFICULDADE = reader["tipo_dificuldade"].ToString();
        result.id_dificuldade = int.Parse(reader["id_dificuldade"].ToString());

    }
    conn.Close();

    return Json(result, JsonRequestBehavior.AllowGet);
}

这是我的视图代码:

@Html.DropDownListFor(model => model.id_cat, ViewBag.ListaCategoria as SelectList, "-- Selecione a Categoria --", new { @class = "form-control" })
@Html.DropDownListFor(model => model.id_dificuldade, new SelectList(" "),  "-- Selecione a Dificuldade --",  new { @class = "form-control"  })

jQuery 代码:

$(document).ready(function () {
    $("#id_cat").change(function () {
        $.get("/Home/Testeeee", { id_cat: $("#id_cat").val() }, function (data) {
            $("#id_dificuldade").empty();
            $.each(data, function (index, row) {
                $("#id_dificuldade").append("<option value='" + row.id_dificuldade + "'>" + row.TIPO_DIFICULDADE + "</option>")
            });
        });
    })
});

我的问题

我的问题是该值在第二个 ComboBox 中返回 undefined,好像该值没有返回或未被识别。

【问题讨论】:

  • 你的控制器方法返回一个dificuldade,而不是一个集合(你不能迭代一个对象)
  • 我怎样才能让它作为一个列表返回?
  • 初始化List&lt;dificuldade&gt; 并使用while (reader.Read())dificuldade 的新实例添加到该集合,然后返回该集合
  • 你能用我的控制器做一个例子吗?如果可以的话,我对 MVC 有点陌生。谢谢 ! ^-^

标签: c# asp.net asp.net-mvc


【解决方案1】:

您的Testeeee() 方法返回dificuldade 的单个实例,而不是集合。更改创建集合的方法,并在读取数据时添加每个

public JsonResult Testeeee(int id_cat )
{
    List<dificuldade> model = new List<dificuldade>();
    ....
    SqlDataReader reader = com.ExecuteReader();
    while (reader.Read())
    {
        dificuldade item = new dificuldade();
        item.TIPO_DIFICULDADE = reader["tipo_dificuldade"].ToString();
        item.id_dificuldade = int.Parse(reader["id_dificuldade"].ToString());
        model.Add(item);
    }
    conn.Close();
    return Json(model, JsonRequestBehavior.AllowGet);
}

附带说明一下,您还有其他问题,包括如果您需要在 POST 方法中返回视图,您将丢失数据,并且如果编辑现有记录,您的代码将不会显示正确的数据。参考How to keep cascade dropdownlist selected items after form submit?

【讨论】:

  • 它工作!非常感谢,我现在明白为什么它不起作用了!!
  • 请不要对我们大喊大叫 :)
猜你喜欢
  • 1970-01-01
  • 2013-04-27
  • 1970-01-01
  • 2021-12-05
  • 2014-04-16
  • 1970-01-01
相关资源
最近更新 更多