使用数据MVC 3 .NET填充多选列表

我一直在谷歌和Stackoverflow上搜索关于如何使用可以选择的值填充多重选择框的解决方案。 但没有运气。

public class PriceObj { public int ID { get; set; } public decimal Price { get; set; } public string Name { get; set; } public string Description { get; set; } public virtual ICollection PriceGroup {get; set;} } public class PriceGroupObj { public int ID { get; set; } public string Name { get; set; } } public class PriceDatabaseContext : DbContext { public DbSet PriceObjs { get; set; } public DbSet PriceGroupObjs { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Conventions.Remove(); modelBuilder.Entity() .HasMany(g => g.PriceGroup) .WithMany() .Map(t => t.MapLeftKey("GroupID").MapRightKey("PriceID").ToTable("PriceGroup")); } } 

然后我希望能够在价格对象的编辑视图中为价格选择所有适当的价格组。 但我没有让它工作,它没有填充MultiSelect框中已经创建的所有组。

这是我在Razor veiw中使用的代码:

 @Html.ListBoxFor(model => model.PriceGroup, Model.PriceGroup.Select(pg => new SelectListItem { Text = pg.Name, Value = pg.ID.ToString() }), new { Multiple = "multiple" }) 

select元素显示在网站上,但没有值可供选择。

请帮我解决一下,我的链条坠落的地方。

使用适合视图要求的视图模型:

 public class PriceViewModel { public int[] SelectedPriceIds { get; set; } public IEnumerable Prices { get; set; } } 

ListBoxFor在视图模型上需要2个属性:

  1. 基本类型的集合属性( string[]id[]Guid[] ,…)将保存所选元素的id
  2. 一个IEnumerable属性,用于保存所有项的列表

然后在视图中:

 @Html.ListBoxFor(x => x.SelectedPriceIds, Model.Prices) 

现在,您的控制器操作会将此视图模型传递给视图,而不是您的域对象,这些对象根本不适合您要实现的目标。 在控制器操作中,您将从域模型填充此视图模型。

我可以在列表框中选择多个值,因此我建议以其他类型执行此操作

你可以像下面这样使用….

你使用这个js文件..

    

这在您的视图中使用

  @Html.ListBoxFor(model => model.CountryId,Model.Countries, new { @class = "chzn-select",data-placeholder="Choose a Country...", Style = "width: 150px;" }) 

你只需绑定你的列表框,然后像这样选择你的多个值。 查看更多关于jquery选择… http://davidwalsh.name/jquery-chosen

在此处输入图像描述

我想这会对你有所帮助..