我正在尝试制作动态下拉列表: 我从数据库中获取下拉列表的选项并将它们放在对象列表中。根据复选框值,我从列表中删除对象并将此列表设置为ViewBag值。
public ActionResult ThematicManagement(string Id, string IsAdult, string flagAdult)
{
.....
ViewBag.DDL = null;
var response = VodCatalogBUS.GetParentThematics();
List<oboThematic> list = new List<oboThematic>();
list = response.Data;
if (IsAdult == null || IsAdult == "false")
list.RemoveAll(x => x.IsAdult == true && x.Id != 1007);
else
list.RemoveAll(x => x.IsAdult == false && x.Id != 1007);
ViewBag.DDL = new SelectList(list, "Id", "Name");
....
然后在我看来,我填写下拉列表:
@Html.DropDownList("ParentThematic", (SelectList)ViewBag.DDL, new { @class="dropdown" })
<label><input type="checkbox" value="" id="ChkIsAdult" name="ChkIsAdult">Adulte</label>
这里没有问题,我在控制器中的RemoveAll之后获得了带有4个选项的下拉列表。然后,如果我点击复选框,我必须获得3个其他选项。
所以我使用ajax调用返回控制器,目的是更新Viewbag的值:
$('#ChkIsAdult').change(function () {
var IsAdult = $('#ChkIsAdult').is(':checked');
var url = dev + "/Legacy/ThematicManagement";
$.ajax({
url: url,
cache: false,
type: 'POST',
data: {
IsAdult: IsAdult,
flagAdult : 'true',
},
success: function () {
alert('test');
}
});
})
它可以返回到控制器,但我认为视图没有刷新,因此我在点击复选框后检索下拉列表的旧值(4个选项)。
我也尝试使用ViewData和TempData替换ViewBag,但我总是使用相同的proprem!
根据你的说法,这是一个很好的解决方案吗?可以吗?
答案 0 :(得分:1)
以下是回复:
控制器
var response = VodCatalogBUS.GetParentThematics();
List<oboThematic> list = new List<oboThematic>();
list = response.Data;
list.RemoveAll(x => x.IsAdult == true && x.Id != 1007);
var responseAdult = VodCatalogBUS.GetParentThematics();
List<oboThematic> listAdult = new List<oboThematic>();
listAdult = responseAdult.Data;
listAdult.RemoveAll(y => y.IsAdult == false && y.Id != 1007);
ViewBag.DDL = new SelectList(list, "Id", "Name");
ViewBag.DDLAdult = new SelectList(listAdult, "Id", "Name");
查看:
@Html.DropDownList("ParentThematic", (SelectList)ViewBag.DDL, new { @class="dropdown" })
@Html.DropDownList("ParentThematicAdult", (SelectList)ViewBag.DDLAdult, new { @class="dropdown" , @style="display:none"})
JS:
$('#ChkIsAdult').change(function () {
if ($('#ChkIsAdult').is(':checked')) {
$('#ParentThematic').hide();
$('#ParentThematicAdult').show();
var value = $('#ParentThematicAdult').val();
var IsAdult = $('#ChkIsAdult').is(':checked');
var url = dev + "/Legacy/ThematicManagement";
$.ajax({
url: url,
cache: false,
type: 'POST',
data: {
Id: value,
IsAdult: IsAdult
},
success: function (data) {
$('#result').empty().append($(data).find('table'))
}
});
}
else
{
$('#ParentThematic').show();
$('#ParentThematicAdult').hide();
var value = $('#ParentThematic').val();
var IsAdult = $('#ChkIsAdult').is(':checked');
var url = dev + "/Legacy/ThematicManagement";
$.ajax({
url: url,
cache: false,
type: 'POST',
data: {
Id: value,
IsAdult: IsAdult
},
success: function (data) {
$('#result').empty().append($(data).find('table'))
}
});
}
})