12

我想编辑一个像下面这样的对象。我希望从 UsersGrossList 中填充一个或多个用户的 UsersSelectedList。

使用 mvc 中的标准编辑视图,我只映射了字符串和布尔值(未在下面显示)。我在 google 上找到的许多示例都使用了 mvc 框架的早期版本,而我使用的是官方 1.0 版本。

任何视图示例都值得赞赏。

public class NewResultsState
{
    public IList<User> UsersGrossList { get; set; }
    public IList<User> UsersSelectedList { get; set; }
}
4

3 回答 3

8

假设 User 模型具有 Id 和 Name 属性:

<%= Html.ListBox("users", Model.UsersGrossList.Select(
    x => new SelectListItem {
        Text = x.Name,
        Value = x.Id,
        Selected = Model.UsersSelectedList.Any(y => y.Id == x.Id)
    }
) %>

或使用视图模型

public class ViewModel {
    public Model YourModel;
    public IEnumerable<SelectListItem> Users;
}

控制器:

var usersGrossList = ...
var model = ...

var viewModel = new ViewModel {
    YourModel = model;
    Users = usersGrossList.Select(
        x => new SelectListItem {
            Text = x.Name,
            Value = x.Id,
            Selected = model.UsersSelectedList.Any(y => y.Id == x.Id)
        }
    }

看法:

<%= Html.ListBox("users", Model.Users ) %>
于 2009-06-15T09:37:09.177 回答
6

将 Html.ListBox 与 IEnumerable SelectListItem 结合使用

看法

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

        <input type="submit" value="submit" name="subform" />
        <% }%>

控制器/型号:

        public List<CategoryInfo> GetCategoryList()
    {
        List<CategoryInfo> categories = new List<CategoryInfo>();
        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<SelectListItem> CategoryList { get; set; }
        public IEnumerable<string> CategoriesSelected { get; set; }

    }
    public ActionResult Category(ProductViewModel model )
    {
      IEnumerable<SelectListItem> 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);
    }
于 2009-06-15T09:31:13.717 回答
1

@ eu-ge-ne < 非常感谢您的回答 - 很难找到一种方法来从模型中多选值列表。使用您的代码,我在编辑/更新页面中使用了 ListBoxFor Html 控件,并在保存时将整个模型传递回我的控制器(包括 mulisple 选择的值)。

<%= Html.ListBoxFor(model => model, Model.UsersGrossList.Select( 
x => new SelectListItem { 
    Text = x.Name, 
    Value = x.Id, 
    Selected = Model.UsersSelectedList.Any(y => y.Id == x.Id) 
} 

) %>

于 2010-05-15T17:58:41.020 回答