viewModelを使用できます。これは、いくつかの仮定を伴うソリューションの例です。ドロップダウンリストを参照してください(ここのドロップダウンには、「InBound」タイプの部門がリストされています。
従業員モデル
public class EmployeeModel
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int DeptId { get; set; }
}
部門モデル
public class DepartmentModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Type { get; set; }
}
ViewModel(ビューに渡されます)
public class EmployeeViewModel
{
public EmployeeModel Employee { get; set; }
public IEnumerable<DepartmentModel> Departments { get; set; }
}
コントローラ
public ActionResult Index()
{
EmployeeViewModel vm = new EmployeeViewModel();
//This is hardcoded. However you will write your own method to pull the department details with filtering
List<DepartmentModel> departments = new List<DepartmentModel>() { new DepartmentModel { Id = 1, Name = "Accounts", Type = "InBound" }, new DepartmentModel { Id = 2, Name = "Finance", Type = "OutBound" }, new DepartmentModel { Id = 3, Name = "HR", Type = "InBound" } };
vm.Departments = departments.Where(d => d.Type == "InBound");
return View(vm);
}
意見
@model Test1.ViewModels.EmployeeViewModel
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@using (Html.BeginForm())
{
@Html.HiddenFor(model => model.Employee.Id);
<table>
<tr>
<td>@Html.LabelFor(model => model.Employee.FirstName)</td>
<td>@Html.EditorFor(model => model.Employee.FirstName)</td>
</tr>
<tr>
<td>@Html.LabelFor(model => model.Employee.LastName)</td>
<td>@Html.EditorFor(model => model.Employee.LastName)</td>
</tr>
<tr>
<td>@Html.Label("Department")</td>
<td>@Html.DropDownListFor(model => model.Employee.DeptId, new SelectList(Model.Departments, "Id", "Name"))</td>
</tr>
</table>
}