我需要使用 JSON 对 2 下拉菜单进行级联,在我应用代码后,在我选择 Category 下拉菜单后,JSON 应该在子类别下拉菜单上查询我的数据。但什么也没有发生。
我的代码做错了吗?
控制器 :
public ActionResult Create()
{
ViewBag.Category = ads.Categories.ToList();
ViewBag.SubCategory = ads.SubCategories.ToList();
return View();
}
private IList<SubCategory> GetSubCategory(int id_category)
{
return ads.SubCategories.Where(m => m.id_category == id_category).ToList();
}
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult LoadSubcategoryByCategory(string id_category)
{
var SubCategoryList = this.GetSubCategory(Convert.ToInt32(id_category));
var SubCategoryData = SubCategoryList.Select(m => new SelectListItem()
{
Text = m.name.ToString(),
Value = m.id.ToString()
});
return Json(SubCategoryData, JsonRequestBehavior.AllowGet);
}
看法 :
<script type="text/javascript">
$(document).ready(function () {
$("#ddlCategory").change(function () {
var category_id = $(this).val();
$.getJSON("../Ads/LoadSubcategoryByCategory", { id_category: category_id },
function (SubCategoryData) {
var select = $("#ddlSubCategory");
select.empty();
select.append($('<option/>', {
value: 0,
text: "-Select a SubCategory-"
}));
$.each(SubCategoryData, function (index, itemData) {
alert(SubCategoryData);
select.append($('<option/>', {
value: itemData.Value,
text: itemData.Text
}));
});
});
});
</script>
<div class="editor-label">
Category :
</div>
<div class="drop-down">
@Html.DropDownListFor(Model => Model.id_category, new SelectList(ViewBag.Category as System.Collections.IEnumerable, "id", "name"),
"-Choose Category-", new { id = "ddlCategory" })
</div>
<div class="editor-label">
Subcategory :
</div>
<div class="drop-down">
@Html.DropDownListFor(Model => Model.id_subcategory, new SelectList(Enumerable.Empty<SelectListItem>(), "id", "name"),
"-Choose SubCategory-", new { id = "ddlSubCategory" })
</div>
希望有人可以帮助我。
更新
在我的控制台 Firefox 节目中
[10:24:59.464] ReferenceError: $ is not defined @ http://localhost:63280/Ads/Create:29
[10:25:03.565] Use of getPreventDefault() is deprecated. Use defaultPrevented instead. @ http://localhost:63280/Scripts/jquery-1.7.1.js:3446
[10:25:08.284] Use of attributes' specified attribute is deprecated. It always returns true. @ http://localhost:63280/Scripts/jquery-1.7.1.js:2378