[英]How to get the value of selected item and insert
我已經編寫了這個簡單的代碼,以便通過Entity Framework
在Web Form
而不是在MVC
插入記錄。 我想從DropdownList
選定項目中插入部門值
上面的數據是手動添加到數據庫中的...如果我要從此處插入記錄,則它正在創建新的數據插槽。 我希望將其添加到從下拉列表中選擇的同一類別內。
碼
public partial class WebForm1 : System.Web.UI.Page
{
EmployeeDbContext db = new EmployeeDbContext();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDownList1.DataSource = db.Departments.ToList();
DropDownList1.DataBind();
}
GridView1.DataSource = db.Departments.Include("Employees").ToList();
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
Employee emp = new Employee(){Name = TextBox1.Text,
Gender= TextBox2.Text,
Salary = float.Parse(TextBox3.Text),
//this retuns '_Page' in ID.
Department =
new Department() { ID = Convert.ToInt32(DropDownList1.SelectedValue)}
};
db.Employees.Add(emp);
db.SaveChanges();
}
}
public class Department
{
public int ID { get; set; }
public string Name { get; set; }
public string Location { get; set; }
public List<Employee> Employees { get; set; }
}
public class Employee
{
public int ID { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public float Salary { get; set; }
public Department Department { get; set; }
}
public class EmployeeDbContext : DbContext
{
public DbSet<Employee> Employees { get; set; }
public DbSet<Department> Departments { get; set; }
}
在這種情況下,您可以選擇的Departments
已經存在,則應該使用並設置FK屬性,而不要設置導航屬性:
public class Employee
{
//add this property
[ForeignKey("Department")]
public int DepartmentId { get; set; }
public Department Department { get; set; }
}
然后在您的代碼中可以執行以下操作:
Employee emp = new Employee(){Name = TextBox1.Text,
Gender= TextBox2.Text,
Salary = float.Parse(TextBox3.Text),
DepartmentId=Convert.ToInt32(DropDownList1.SelectedValue)
};
db.Employees.Add(emp);
db.SaveChanges();
只需設置該屬性,即可將當前部門與新員工聯系起來。
現在我看到您在獲取部門ID時遇到問題,在這種情況下,您可以按照@Mike在他的答案中的建議進行操作,也可以在頁面中執行此操作:
<asp:DropDownList ID="DepartmentsDropDownList" runat="server" DataTextField="Name" DataValueField="ID" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.