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) –