[英]Set selected value on SelectList not working
Aparently this is a simple question already answered on SO but I cannot make it work in my code.显然,这是一个已经在 SO 上回答的简单问题,但我无法让它在我的代码中工作。
I want to be able to pre select the first element showed on a SelectList on my view.我希望能够在我的视图中预先选择 SelectList 上显示的第一个元素。
My Controller:我的控制器:
public ActionResult Create(){
CostumerRegister rModel = new CostumerRegister();
rModel.AllStores = getStoresForUser(User.Identity.GetUserId());
//to auto select the first element of the select list
rModel.AllStores.First().Selected = true;
return View(rModel);
}
public SelectList getStoresForUser(string userId){
//...
}
On my View:在我看来:
@Html.ListBoxFor(m => m.SelectedStores, Model.AllStores, new { @class = "form-control" })
I would expect to have the first element selected on the view but it appears not selected.我希望在视图上选择第一个元素,但它似乎没有被选中。
use this one I think its useful:使用这个我认为它有用的:
public ActionResult Index()
{
// Preselect items with id 1 and 3
var selectedItemIds = new[] { 1, 3 };
var model = new MyViewModel
{
Items = new MultiSelectList(
new[]
{
// TODO: Fetch from your repository
new { Id = 1, Name = "item 1" },
new { Id = 2, Name = "item 2" },
new { Id = 3, Name = "item 3" },
},
"Id",
"Name",
selectedItemIds
)
};
return View(model);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.