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; }
}
}
我使用數據庫第一種方法。
相關代碼需要在問題中。不是它的圖像。 –
這些是粘貼bin鏈接。不是圖像。無論如何,我會添加代碼的問題。 – JayNaz
通過使用一個視圖模型開始,該視圖模型將包含一個屬性'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) –