繁体   English   中英

在 SelectList 上设置选定的值不起作用

[英]Set selected value on SelectList not working

显然,这是一个已经在 SO 上回答的简单问题,但我无法让它在我的代码中工作。

我希望能够在我的视图中预先选择 SelectList 上显示的第一个元素。

我的控制器:

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){
//...
}

在我看来:

@Html.ListBoxFor(m => m.SelectedStores, Model.AllStores, new { @class = "form-control" })

我希望在视图上选择第一个元素,但它似乎没有被选中。

使用这个我认为它有用的:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM