我的观点中有两个@Html.ListBox
:
IEnumerable<Models.CategoryModel> categories = ViewBag.AllCategories;
IEnumerable<Models.TypeModel> types = ViewBag.AllTypes;
@Html.Label("Category", new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.ListBox("CategoriesFilter", new MultiSelectList(categories, "CatID", "Category"), new { @class = "chosen-select" })
</div>
@Html.Label("Type", new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.ListBox("TypesFilter", new MultiSelectList(types, "TID", "Description"), new { @class = "chosen-select" })
</div>
当用户选择/取消选择类别时,我需要刷新@Html.ListBox("TypesFilter")
中的类型。我正在进行如下的ajax调用:
$("#CategoriesFilter").change(function () {
setTypesByCategory();
});
function setTypesByCategory() {
var categoryIDs = ($('#CategoriesFilter').val());
$.ajax({
url: "@(Url.Action("SetTypesByCategory", "Issues"))",
type: "POST",
contentType: 'application/json; charset=utf-8',
data: '{ "categoryIDs" : "' + categoryIDs + '" }',
success: function (data) {
$.each(data, function () {
$.each(this, function (k, v) {
window.alert("success !!!" + k + " test " + this.STID);
});
});
$("#TypesFilter").empty();
$("#TypesFilter").val(data.TypesData);
}
});
}
在我的控制器中:
[System.Web.Mvc.HttpPost]
public JsonResult SetTypesByCategory(string categoryIDs)
{
string[] categories = categoryIDs.Split(',');
List<TypeModel> filterdTypesList = new List<TypeModel>();
foreach (var catID in categories)
{
foreach (var type in types.Where(m => m.CatID == Int32.Parse(catID)))
{
filterdTypesList.Add(type);
}
}
int modelCount = filterdTypesList.Count();
IEnumerable<TypeModel> filterdTypes = filterdTypesList;
return Json(new { TypesData = filterdTypes, ModelCount = modelCount });
}
首先,使用$("#TypesFilter").empty();
时,类型列表框不为空。如何用获得的结果填充此列表框?