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

Gun*_*nar 1 c# sql-server asp.net asp.net-mvc entity-framework

我一直在Google和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<PriceGroupObj> PriceGroup {get; set;}
}

public class PriceGroupObj
{
   public int ID { get; set; }
   public string Name { get; set; }
}


public class PriceDatabaseContext : DbContext
{
    public DbSet<PriceObj> PriceObjs { get; set; }
    public DbSet<PriceGroupObj> PriceGroupObjs { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Conventions.Remove<System.Data.Entity.ModelConfiguration.Conventions.PluralizingTableNameConvention>();

        modelBuilder.Entity<PriceObj>()
            .HasMany(g => g.PriceGroup)
            .WithMany()
            .Map(t => t.MapLeftKey("GroupID").MapRightKey("PriceID").ToTable("PriceGroup"));
    }


}
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

请帮我理清,我的链条在哪里.

Dar*_*rov 11

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

public class PriceViewModel
{
    public int[] SelectedPriceIds { get; set; }
    public IEnumerable<SelectListItem> Prices { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

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

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

然后在视图中:

@Html.ListBoxFor(x => x.SelectedPriceIds, Model.Prices)
Run Code Online (Sandbox Code Playgroud)

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