【发布时间】:2019-05-15 04:06:02
【问题描述】:
我在一个页面上有 2 个下拉列表。当我从第一个下拉列表中选择某个值时,然后在第二个下拉列表中,所有值都应根据所选值加载(根据类别加载子类别)。这是我尝试过的,但它不起作用:
型号
public class Product
{ ...
public int CategoryId { get; set; }
public virtual Category Category { get; set; }
public IEnumerable<SelectListItem> Categories { get; set; }
public int SubCategoryId { get; set; }
public virtual SubCategory SubCategory { get; set; }
public IEnumerable<SelectListItem> SubCategories { get; set; }
...
}
查看
<label>Select Category</label>
@Html.DropDownListFor(m => m.CategoryId, new SelectList(Model.Categories, "Value", "Text"), "Select Category", new { id = "catList", @class = "form-control" })
<label>Selectat Subcategory</label>
@Html.DropDownListFor(m => m.SubCategoryId, new SelectList(Enumerable.Empty<SelectListItem>(), "Value", "Text"), "Selectat Subcategory", new { id = "subcatList", @class = "form-control" })
<script type="text/javascript">
$(document).ready(function () {
$("#catList").change(function () {
var cID = $(this).val();
$.getJSON("../Product/New/LoadSubCategories", { catId: cID },
function (data) {
var select = $("#subcatList");
select.empty();
select.append($('<option/>', {
value: 0,
text: "Selecteaza o subcategorie"
}));
$.each(data, function (index, itemData) {
select.append($('<option/>', {
value: itemData.Value,
text: itemData.Text
}));
});
});
});
});
</script>
控制器
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult LoadSubCategories(string catId)
{
var subCatList = GetAllSubCategories(Convert.ToInt32(catId));
return Json(subCatList, JsonRequestBehavior.AllowGet);
}
[NonAction]
public IEnumerable<SelectListItem> GetAllSubCategories(int selectedCatId)
{
//generate empty list
var selectList = new List<SelectListItem>();
var subcategories = from sbcat in db.SubCategories
where sbcat.CategoryId == selectedCatId
select sbcat;
foreach (var subcategory in subcategories)
{
//add elements in dropdown
selectList.Add(new SelectListItem
{
Value = subcategory.SubCategoryId.ToString(),
Text = subcategory.SubCategoryName.ToString()
});
}
return selectList;
}
【问题讨论】:
-
那么您当前的代码发生了什么?您是否看到任何脚本错误?你的网络通话成功了吗?
标签: c# jquery asp.net-mvc model-view-controller