2012-04-11 39 views
0

我已經創建了mvc3應用程序。 使用EF從表中填充下拉列表的位置。如何從兩個表中動態地在mvc3中填充dropdownlist?

現在我有two dropdownlists在我的index.cshtml每個填充從不同的表。

代碼index.cshtml:

,因爲它同時具有我的表table1table2

@model Mapping.Models.mydataEntities1

但問題我已經採取了模型的實體在這裏我不能夠選擇的值來自兩個表格。 :(

像下面的代碼是唯一的工作時,我給 模式@model Mapping.Models.table1

,但需要從不同的表

@using (Html.BeginForm()) 
{ 
    @Html.DropDownListFor(
     x => x.CategoryId, 
     new SelectList(Model.Categories, "Value", "Text"), 
     "-- Select category --" 
    ) 
    <input type="submit" value="OK" /> 
} 

我怎樣才能做到這一點?

選擇值分爲兩個下拉列表

我已使用EF

public partial class mydataEntities1 : DbContext 
    { 
     public mydataEntities1() 
      : base("name=mydataEntities1") 
     { 
     } 

     protected override void OnModelCreating(DbModelBuilder modelBuilder) 
     { 
      throw new UnintentionalCodeFirstException(); 
     } 

     public DbSet<table1> table1 { get; set; } 
     public DbSet<table2> table2 { get; set; } 
    } 
} 
+0

安置自己的模型'mydataEntities1'。如果它有兩張表格填充正確,它應該可以工作 – Iridio 2012-04-11 16:07:41

+0

@Iridio請參閱我已更新問題 – Neo 2012-04-11 16:12:50

+0

使用ViewModel @Iron Ninja節目並閱讀http://blogs.msdn.com/b/rickandy/archive/2012/01 /09/cascasding-dropdownlist-in-asp-net-mvc.aspx - 另請參閱http://www.asp.net/mvc/tutorials/javascript/working-with-the-dropdownlist-box-and-jquery/using -the-dropdownlist-helper-with-aspnet-mvc如果有任何東西丟失,請告訴我,我會添加它 – RickAndMSFT 2012-04-11 16:17:32

回答

1

我不是EF用戶,但假設你的模型填充和作品正確 下面的代碼應該工作

@Html.DropDownListFor(
    x => x.table1.CategoryId, 
    new SelectList(Model.table1.Categories, "Value", "Text"), 
    "-- Select category --" 
) 

@Html.DropDownListFor(
    x => x.table2.CategoryId, 
    new SelectList(Model.table2.Categories, "Value", "Text"), 
    "-- Select category --" 
) 

但我強烈reccomend您創建一個視圖模型將數據暴露在視圖,而不是你的域實體,或直接存儲庫。

1

我建議有一個實際的'模型',而不是直接將數據實體直接推入視圖。像這樣的東西可能是你應該用什麼模型:

public class MyModel 
{ 
    public Mapping.Models.table1 table1; 
    public Mapping.Models.table2 table2; 
} 

,然後你的模型將成爲

@model MyModel 
0

視圖代碼

<%: Html.DropDownList("courses","--select--")%> 

控制器代碼

公共的ActionResult指數() {的NewClass NW =新的NewClass();

 IEnumerable<SelectListItem> lt = nw.method().Select(c => new SelectListItem 
     { 
      Text = c.EmpName, 
      Value = c.EmpId.ToString() 
     }); 
     ViewData["courses"] = lt; 

     return View(); 
    } 

模型代碼

公共類的NewClass { DataClasses2DataContext分貝=新DataClasses2DataContext(); (); public IEnumerable method() {LTO} {(從db.Employees中的val選擇新的Class1 {EmpName = val.EmpName,EmpId = val.EmpId})。Distinct()。ToList();如果(lt!= null) var values = from val in val order by val。EmpId選擇val; 返回值;其他 返回null; }

} 
public class Class1 
{ 

    public int EmpId{get;set;} 
    public string EmpName { get; set; } 
    public string location { get; set; } 
    public Int64 Phno{get;set;} 

} 

插件模型類的命名空間到控制器,並嘗試它希望這將很好地工作在asp.net MVC3填寫下拉列表