gpt4 book ai didi

c# - ASP.NET MVC 级联组合框

转载 作者:太空宇宙 更新时间:2023-11-03 14:59:27 25 4
gpt4 key购买 nike

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

根据第一个组合框的选择填充第二个组合框的 Controller 方法代码

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

这是我的 View 代码:

@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,就好像该值没有返回或未被识别一样。

最佳答案

您的 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 方法中返回 View ,您将丢失数据,并且如果编辑现有记录,您的代码将不会显示正确的数据。引用How to keep cascade dropdownlist selected items after form submit?

关于c# - ASP.NET MVC 级联组合框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46929628/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com