我有一个多选下拉列表,下拉列表的值来自数据库。如何使用多个选定值填充多选下拉列表。
我在控制器中的viewbag
var app_dependent = (from ao in db.mas_app_dependent
where ao.app_key == id // id is app_key(PK) value=1
select ao.app_dependent__key).ToList();
ViewBag.app_key = new SelectList(db.mas_apps, "app_key", "app_name", app_dependent);
我在index.cshtml页面中的视图
<div class="form-group">
<label id="ownerbiz" class="control-label col-md-2">Dependent Application</label>
<div class="col-md-10">
@Html.DropDownList("app_key", null, "--Select--", htmlAttributes: new { @class = "form-control e1", @multiple = "multiple", @placeholder = "Select / Search here!" })
</div>
我的db.mas_apps表值
app_key(PK) app_name
1 CRTS
2 CITRIX
12 Hiport
15 Frig
变量app_dependent的db.mas_app_dependent值
dep_key(PK) app_key dependent_app_key
1 1 2
12 1 12
答案 0 :(得分:1)
我使用
绑定bootstrap multiselect和数据库值for state在Controller Action Menthod中
[HttpGet]
public ActionResult ManageShippers()
{
var stateList = db.states.ToList();
ViewBag.State = new SelectList(stateList, "StateId", "StateName");
}
在视图内
@Html.DropDownList("ddlMultiSelectState", ViewBag.State as SelectList, new { @id = "ddlMultiSelectState", Name = "Select State", @class = "form-control", @multiple = "multiple" })
它的作品。
答案 1 :(得分:0)
您确实需要使用包含所选值和选项集合
属性的视图模型public class MyVM
{
public int[] SelectedValues { get; set; }
public SelectList AllValues { get; set; }
}
然后在控制器中
var app_dependent = (from ao in db.mas_app_dependent
where ao.app_key == id // id is app_key(PK) value=1
select ao.app_dependent__key).ToArray();
MyVM model = new MyVM();
model.SelectedValues = app_dependent;
model.AllValues = new SelectList(db.mas_apps, "app_key", "app_name");
return View(model);
并在视图中
@Html.ListBoxFor(m => m.SelectedValues, Model.AllValues, new { @class = "form-control e1" })
注意ListBoxFor()
添加`multiple =“multiple”属性
如果SelectedValues
包含(比方说)[2, 12]
,则在呈现视图时将选择第2和第4个选项。
答案 2 :(得分:0)
var dependent = (from ad in db.mas_app_dependent
where ad.app_key == id && ad.inactive==true
select ad.dependent_app_key).ToArray();
ViewBag.app_key = new MultiSelectList(db.mas_apps, "app_key", "app_name", dependent);-----viewbag for dropdown
在视图中
@Html.DropDownList("app_key", null, "--Select--", htmlAttributes: new { @class = "form-control e1", @multiple = "multiple", @placeholder = "Select / Search here!", id="dependent" })
创建隐藏元素
@Html.Hidden("hdn_dependent")
我们可以通过在下拉列表中创建ID来获取所选下拉列表中的值。并使用jquery来计算多选下拉列表中的选定值
var dep = $('#dependent').val().toString();
$("#hdn_dependent").val(dep);