【问题标题】:Set selected value on SelectList not working在 SelectList 上设置所选值不起作用
【发布时间】:2019-04-27 07:55:48
【问题描述】:

显然这是一个已经在 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" })

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

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-4 razor


    【解决方案1】:

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

    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);
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-09
      • 2015-02-23
      • 1970-01-01
      • 2021-05-17
      相关资源
      最近更新 更多