我使用ASP.NET MVC 5开发一个网站,使用Chosen.js进行多选。我的行动是:
[HttpGet]
public ActionResult Get()
{
var states = GetStates();
ViewBag.States = new SelectList(states.OrderBy(o => o.Id), "Value", "Name");
return View();
}
在视图中:
@Html.ListBoxFor(m => m.States,
ViewBag.States as SelectList, new Dictionary<string, object>
{
{"multiple", "multiple"},
{"class", "chosen-container-multi"},
{"placeholder", "State"},
{"id", "State"}
});
它工作正常,但我想在加载页面之前选择用户状态。也许是这样的事情:
ViewBag.States = new SelectList(states.OrderBy(o => o.Id), "Value", "Name","UserStateId");
但它不起作用。有没有办法做到这一点?
答案 0 :(得分:1)
首先,您不能将ViewBag
属性命名为与您的模型属性相同。您的列表框绑定到您的模型属性States
,因此所选的选项将基于States
的值。由于您未将模型返回到视图States
,因此无法选择任何选项。
首先使用一个视图模型来表示您想在视图中显示/编辑的内容
public class MyViewModel
{
public int[] SelectedStates { get; set; }
public SelectList StatesList { get; set; }
}
控制器(注意我假设State
包含属性int Id
(要绑定到)和属性string Name
(显示值),并且您要预先选择状态为Id=2
和Id=5
)
[HttpGet]
public ActionResult Get()
{
MyViewModel model = new MyViewModel();
var states = GetStates().OrderBy(o => o.Id);
model.StatesList = new SelectList(states, "Id", "Name");
model.SelectedStates = new int[] { 2, 5 }; // set the value of the options you want to preselect
return View(model);
}
查看
@Html.ListBoxFor(m => m.SelectedStates, Model.StatesList, new { @class = "chosen-container-multi" })
假设您有10个状态Id
介于1和10之间,那么现在将在首次渲染页面时选择第2和第5个选项。提交表单时,属性SelectedStates
将包含用户选择的值和数组。
附注:ListBoxFor()
已添加属性multiple="multiple"
和id="SelectedStates"
答案 1 :(得分:-1)
我采用了这种方法:
在名为UserState
的模型上创建了一个新的字符串属性,然后我获得了用户状态并将其分配给该属性:
ViewBag.States= new SelectList(states.OrderBy(o => o.Id), "Value", "Name");
var model = new ModelDTO { UserState = states.Single(p => p.Id.Equals(stateId)).Value};
return View(model);
然后在视图上我简单地得到它:
@Html.ListBoxFor(m => m.States,
ViewBag.States as SelectList, new Dictionary<string, object>
{
{"multiple", "multiple"},
{"class", "chosen-container-multi"},
{"placeholder", "State"},
{"id", "State"}
});
<script>
$(function () {
$("#StatesListBox").chosen();
$('#StatesListBox').val("@Model.UserState");
$('#StatesListBox').trigger("chosen:updated");
});
</script>