你需要創建一個ViewModel
這樣的:
public class EmployeeViewModel
{
public string Name { get; set; }
[Required(ErrorMessage = "...")] // to protect against under-posting attacks
[Display(Name = "Department")]
public int? DepartmentId { get; set; }
public IEnumerable<SelectListItem> Departments { get; set; }
}
控制器:
public ActionResult Create()
{
var employeeViewModel = new EmployeeViewModel();
employeeViewModel.Departments = GetDepartments().Select(option => new SelectListItem
{
Text = option.name,
Value = option.Id.ToString()
});
return View(employeeViewModel);
}
// Post
public ActionResult Create(EmployeeViewModel model)
{
// Map ViewModel to Entity and Save to db...
}
查看:
@model EmployeViewModel
<div class="form-group">
@Html.LabelFor(model => model.Name)
@Html.TextBoxFor(model => model.Name, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="form-group">
@Html.LabelFor(model => model.DepartmentId)
@Html.DropDownListFor(model => model.DepartmentId, Model.Departments, "Choose...")
@Html.ValidationMessageFor(model => model.DepartmentId)
</div>
不創建一個 '局部'類。你創建一個視圖模型 - [什麼是MVC中的ViewModel?](http://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc)。而對於典型的iplementation,請參考[這個問題/答案](http://stackoverflow.com/questions/34366305/the-viewdata-item-that-has-the-key-xxx-is-of-type-system- int32-but-must-o-o) –