How to Bind Drodown data in MVC Cshtml page in c#
First u consider Employee and Department Tables
DepartmentContext :
--------------------
Employee
Department
Employee
------------------
Id
name
departmentId Foreign key From Department table
Department:
--------------------
id
name
View Model:
EmployeeDepartment
------------------------
Id
name
EmployeeId
EmployeeNames
In Controller code:
---------------------------------
Public ActionResult GSVActoionMethod()
{
DepartmentContext db=new DepartmentContext ();
var employeeDepartments=db.Department.Select(a=> new EmployeeDepartment(){
Id = a.id,
name=a.name,
EmployeeNames=db.Employees.Where(m=>m.departmentId == a.id).ToList()
})
return View(employeeDepartments);
}
In ViewPage :GSVActoionMethod.cshtml
------------------------------------------------------
@model MySample.Models.EmployeeDepartment
@{
ViewData.Name="GSV"
}
<H1>GSV</H1>
@using(Html.BeginForm())
{
@Html.AntiForeignKeyToken()
@Html.ValidationSummary()
<div>
@Html.Label("Select Employee",new {@class="from-contol"})
<div class="form-group">
@Html.DropDownListFor (m=>m.EmployeeId,new SelectList(Model.EmployeeNames,"Id","Name"),new {@class="form-control"})
</div>
</div>
}
veru useful materail sreenivas thank you.
ReplyDeleteThank you
ReplyDeleteFlow of explanation is very good and keep it up Sreenivas
ReplyDelete