将查找值传递到下拉列表的最佳方法

时间:2016-07-22 13:09:48

标签: asp.net-mvc razor

我想知道将查找值列表传递给MVC中的视图的一般方法。目前我有2个db表,我正在使用db first EF6接口。我的主表有一个查找表,我想用查找的所有值填充我的视图的下拉列表,以便用户在创建和编辑时可以选择。

员工表

id primary key
name varchar
department id - this is the id of the department in the lookup

部门表

id primary key
name varchar

最好为员工模型创建一个部分类并添加一个名为allDepartments的新属性,然后在我的控制器中调用一个方法,该方法在将模型传递给视图之前获取所有部门,或者更好地转储部门在viewbag / viewdata字典中。

这里的一般方法是什么?

1 个答案:

答案 0 :(得分:0)

您需要像这样创建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>