Reputation: 1984
I am a newbie to MVC, I have some problem to populate a dropdown inside of a html table. I have my classes like
Public Class Employee
{
public int EmployeeId {get; set;}
public string EmployeeName {get; set;}
public string Country {get; set;}
public Employee() {}
public Employee(Employees emp)
{
this.EmployeeId=emp.EmployeeId;
this.EmployeeName=emp.EmployeeName;
this.Country=emp.Country;
}
}
Public Class Employees : List<Employee>
{
Public Employees()
{
MyEntities entities=new MyEntities();
foreach(Employees emp in entities.Employees)
{
this.Add(new Employee(emp));
}
}
}
In the same way I have Country and Countries classes
also which is having CountryId and CountryName
. I am binding list of Employees in my View from the controller like,
public ActionResult Index()
{
Employees emp = new Employees();
return View(emp);
}
this is showing me the employees data from my db. In the last row of my table I have manually added a row for Adding a new employee
, by entering the EmployeeName
and selecting Country
from a dropdownlist.
The problem is here in the dropdown. I have already displayed a list of employees in my view. Is it possible to one more list of Countries
in my dropdown. And also I need to bind the selected country to the employee.country
property.
I am much more comfortable with webforms, but in MVC I dont know how to achieve this. Can anyone help me out here. Thanks in advance.
Upvotes: 0
Views: 2014
Reputation: 650
Try This one.....
View
@Html.DropDownList("Cert", (SelectList)ViewData["Countries"], "--Select--", new { @class="dropdownlist" ,id = "Country" })
Models
public string Certification{ get; set; }
Controller
var Country = new SelectList(new[]
{
new {ID="1",Name="India"},
new{ID="2",Name="Nepal"},
new{ID="3",Name="Srilanka"},...etc
});
ViewData["Countries"] = Country ;
Upvotes: 1
Reputation: 100620
Instead of just Employees
pass model that contain both collections:
class IndexViewModel
{
public IEnumerable<Employee> Employees {get;set;}
public IEnymerable<Conuntry> Countries {get;set;}
}
Than construct and pass it to view
return View(new IndexViewModel {
Employees = employeeRepository.GetAll(),
Countries = GetAllCountries()
}
Than render countries dropdown using Model.Countries
Upvotes: 1