I have two tables whose structure is as follows:
Employee:
int Id
string EmployeeName
string Department
Department:
int Dept_Id
string Department
Department Table Stores All the Departments with their respective id, and i have a registration form of Employee which contains DropDownList. I want to populate all of the departments as soon as the form loads in the dropdown for that i have to call two models on the same view. I was using tuple but it does not solve my problem. Please help to solve my problem. Code that i am using is :
public ActionResult Index()
{
var model = new model<Employee, Department>(new Employee(), new Department());
return View(model);
}
@model Tuple<MVcEmpApp.Models.Employee, MVcEmpApp.Models.Department>
[HttpPost]
public ActionResult InsertRecord(MyViewModel model)
{
if(ModelState.IsValid)
{
var Employee=new Employee();
Employee.EmployeeName=model.employee.EmployeeName;
Employee.Department=model.employee.Department;
db.AddToEmployee(Employee);
db.SaveChanges();
}
}
Please give any suggestions, Thanks for your answers....
You can create a single ViewModel
wrapper class which holds your two models. Read What is ViewModel in MVC?
public class MyViewModel
{
public Employee employee{get;set;}
public Department dept{get;set;}
}
Controller
public ActionResult Index()
{
var model = new MyViewModel{employee=new Employee(), dept=new Department()}
return View(model);
}
In your view
@model MyViewModel
<label>First Name</label>
@Html.TextBoxFor(m=>m.Employee.FirstName)
I would create two classes Employee and Department as entities.
Your model then would be
public class MyModel
{
public Employee employee {get; set;}
public List<Department> departments {get; set;}
}
You can in this scenario wire up your dropdown to the departments. You will want to add javascript to populate a hidden field on your page with the selected value - which you can wireup to the employee's department id field. This way when you submit your form your action can be written as -
public ActionResult Submit(Employee employee) { .... }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.