How can a multi-select-list be edited using asp.net mvc?

前端 未结 3 390
时光取名叫无心
时光取名叫无心 2021-02-02 01:00

I\'d like to edit an object like the one below. I\'d like the UsersSelectedList populated with one or more Users from the UsersGrossList.

Using the standard edit-views i

3条回答
  •  礼貌的吻别
    2021-02-02 01:41

    Use Html.ListBox in combination with IEnumerable SelectListItem

    View

             <% using (Html.BeginForm("Category", "Home",
          null,
          FormMethod.Post))
           { %>  
            <%= Html.ListBox("CategoriesSelected",Model.CategoryList )%>
    
            
            <% }%>
    

    Controller/Model:

            public List GetCategoryList()
        {
            List categories = new List();
            categories.Add( new CategoryInfo{ Name="Beverages", Key="Beverages"});
            categories.Add( new CategoryInfo{ Name="Food", Key="Food"});
            categories.Add(new CategoryInfo { Name = "Food1", Key = "Food1" });
            categories.Add(new CategoryInfo { Name = "Food2", Key = "Food2" });
            return categories;
        }
    
        public class ProductViewModel
        {
            public IEnumerable CategoryList { get; set; }
            public IEnumerable CategoriesSelected { get; set; }
    
        }
        public ActionResult Category(ProductViewModel model )
        {
          IEnumerable categoryList =
                                    from category in GetCategoryList()
                                    select new SelectListItem
                                    {
                                        Text = category.Name,
                                        Value = category.Key,
                                        Selected = (category.Key.StartsWith("Food"))
                                    };
          model.CategoryList = categoryList;
    
          return View(model);
        }
    

提交回复
热议问题