[英]How to get the value of selected item and insert
I have made this simple code to insert a record through Entity Framework
in Web Form
not in MVC
. 我已经编写了这个简单的代码,以便通过Entity Framework
在Web Form
而不是在MVC
插入记录。 I want to insert the department value from selected item from DropdownList
我想从DropdownList
选定项目中插入部门值
above data is manually added in database... If I am inserting record from here.. it is creating new slot of data. 上面的数据是手动添加到数据库中的...如果我要从此处插入记录,则它正在创建新的数据插槽。 I want that to be added inside the same category which is selected from dropdown. 我希望将其添加到从下拉列表中选择的同一类别内。
Code 码
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; }
}
In this case where the Departments
you can choose already exist, you should use and set a FK property instead of set the navigation property: 在这种情况下,您可以选择的Departments
已经存在,则应该使用并设置FK属性,而不要设置导航属性:
public class Employee
{
//add this property
[ForeignKey("Department")]
public int DepartmentId { get; set; }
public Department Department { get; set; }
}
And then in your code you can do this: 然后在您的代码中可以执行以下操作:
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();
Setting that property is the only you need to do to relate the current department with the new employee. 只需设置该属性,即可将当前部门与新员工联系起来。
Now I saw you are having problems to get the Department Id, in that case you can follow what @Mike recommends in his answer or you can also do this in your page: 现在我看到您在获取部门ID时遇到问题,在这种情况下,您可以按照@Mike在他的答案中的建议进行操作,也可以在页面中执行此操作:
<asp:DropDownList ID="DepartmentsDropDownList" runat="server" DataTextField="Name" DataValueField="ID" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.