2016-07-01 21 views
0

我試圖使用實體框架6開發ASP.net mvc應用程序。 有2個實體Driver & DriverType。在向數據庫添加新驅動程序時,用戶應該能夠從DropDownList中選擇驅動程序類型。 提交表單時,應將所選DriverType的ID添加到Driver表中的DriverTypeID(外鍵)列中。從可以向數據庫提交值的數據庫填充@ Html.DropDownListFor()

我的問題是如何在加載頁面時將所有DriverTypes提取到DropDownList &如何將所選DriverType的ID傳遞給Driver表?

我的模型類如下。

驅動程序類

public partial class Driver 
{ 
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] 
    public Driver() 
    { 
     this.trip_tab = new HashSet<Trip>(); 

    } 

    public string ID { get; set; } 
    public string DriverTypeID { get; set; } 
    public string VehicleID { get; set; } 
    public string Name { get; set; } 
    public string ContactNo { get; set; } 
    public string Comment { get; set; } 

    public virtual DriverType drivertype_tab { get; set; } 

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] 
    public virtual ICollection<Trip> trip_tab { get; set; } 
} 

驅動程序類型類

public partial class DriverType 
{ 
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] 
    public DriverType() 
    { 
     this.driver_tab = new HashSet<Driver>(); 
    } 

    public string ID { get; set; } 
    public string Type { get; set; } 
    public string Comment { get; set; } 

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] 
    public virtual ICollection<Driver> driver_tab { get; set; } 
} 

}

我使用數據庫第一種方法。

+0

相關代碼需要在問題中。不是它的圖像。 –

+0

這些是粘貼bin鏈接。不是圖像。無論如何,我會添加代碼的問題。 – JayNaz

+0

通過使用一個視圖模型開始,該視圖模型將包含一個屬性'int SelectedDriver'和'IEnumerable DriverList'(並使用db.DriverTypes.Select(x => new SelectListItem(){Value = x)填充'DriverList'。 ID,Text = x.Type});'然後參考代碼[這個問題/答案](http://stackoverflow.com/questions/34366305/the-viewdata-item-that-has-the-key-xxx -is-of-type-system-int32-but-must-o -o) –

回答

0

您可以在您的操作中創建一個selectList,並將此selectList傳遞給ViewBag,然後在您的視圖中訪問此ViewBag。你應該在你的行動首先做到這一點:

var allDriverTypes=_driverTypeService.GetAll(); 
ViewBag.DriverTypes=new SelectList(allDriverTypes,"ID","Title"); 

現在考慮你應該這樣做:

@Html.DropDownListFor(model => model.DriverTypeID,(SelectList)ViewBag.DriverTypes) 

做到這一點後,當您的表單提交,回來後控制器,你可以看到driverTypeId用戶選擇綁定到你的模型。

注意:當你創建一個selectList時,你有一個包含你想在下拉列表中顯示的ID和標題的列表。