【发布时间】:2017-08-23 07:24:52
【问题描述】:
我有一张有很多 DropDownList 的表,我根据迭代更改了每个类名:
<table id="categoryTable" class="table table-striped table-hover">
<tr class="header">
<th>
@Html.DisplayNameFor(model => model.Category)
</th>
<th>
@Html.DisplayNameFor(model => model.SubCategory)
</th>
<th>New Category</th>
<th>New Subcategory</th>
<th></th>
</tr>
@if (Model != null) { int i = 1; foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Category)
</td>
<td>
@Html.DisplayFor(modelItem => item.SubCategory)
</td>
<td>
<input type="hidden" class="varIteration" value="@i" /> @Html.DropDownList("CategoryId", null, "Select Your Category", htmlAttributes: new { @class = "form-control Category" + i })
</td>
<td>
<input type="hidden" class=@( "SubCategoryID_CategoryID_initial"+@i) value="@i" /> @Html.DropDownList("SubCategoryId", null, "Select Your Subcategory", htmlAttributes: new { @class = "form-control SubCategory" + i })
</td>
<td>
<button type="submit" class="btn">
<i class="fa fa-check"> Update</i>
</button>
@*
<input type="submit" value="Save" class="fa fa-check" />*@
</td>
</tr>
i++; } }
</table>
我需要使用下面的下一个脚本根据类别中的选定值更改子类别值,该脚本仅适用于第一个类别下拉列表:
$(document).ready(function(e) {
var iteration = $(".varIteration").val(); // iteration = 1 only
getSubCat(true, $(".SubCategoryID_CategoryID_initial" + iteration).val(), iteration);
$(document).on("change", ".Category" + iteration, function(event) {
getSubCat(false, $(".Category" + iteration).val(), iteration);
});
function getSubCat(load, changed, iteration) {
alert(iteration)
var url = "/auc.accesscontrol/profiles/GetSubCatIDByCatID";
var initialSubCat = $(".SubCategoryID_CategoryID_initial").val();
var initialCat = $(".SubCategoryID_SubCategoryID_initial").val();
if (load) {
$('.Category' + iteration + ' option[value="' + initialCat + '"]').prop("selected", true);
}
if (initialCat == null) {
changed = $(".Category" + iteration).val();
}
$.getJSON(url, {
id: changed
}, function(data) {
alert(changed);
$(".SubCategory" + iteration).empty();
$(".SubCategory" + iteration).append("<option value= '0'>Select Your Subcategory</option>");
$.each(data, function(index, item) {
$(".SubCategory" + iteration).append("<option value='" + item.SubCategoryId + "'>" + item.Name + "</option>");
$('.SubCategory' + iteration + ' option[value="' + initialSubCat + '"]').prop("selected", true);
});
});
};
});
当我检查视图类名称时,会发现以下类别的下拉列表:Category1、Category2 等
和子类别:SubCategory1, Subcategory2, ....etc
隐藏的输入值:将根据最后一个 i 而改变。
需要帮助来根据所选类别下拉列表更改迭代变量。
编辑: 这是 JsonResult 函数:
public JsonResult GetSubCatIDByCatID(int id)
{
db.Configuration.ProxyCreationEnabled = false;
var subCategoryList = db.SubCategory.Where(m => m.CategoryId == id).ToList();
return Json(subCategoryList, JsonRequestBehavior.AllowGet);
}
【问题讨论】:
-
当您说它“不起作用”时,当您调试它时,它具体在做什么?观察到的行为与预期行为究竟哪里不匹配?
-
只有在第一个类别下拉列表中才能正常工作,并且子类别将正确过滤...再次在第一个
<tr> -
迭代变量总是等于1
-
点击任何其他下拉列表时没有任何反应
标签: javascript jquery html razor asp.net-mvc-5