在viewmodels中填充SelectLists

时间:2013-08-07 14:41:10

标签: asp.net-mvc viewmodel selectlist

我有一个由以下模型表示的遗留表:

public class Employee
{
    [Key]
    [Column("employee_id")]
    public string EmployeeId { get; set; }

    [Column("first_name")]
    public string FirstName { get; set; }

    [Column("last_name")]
    public string LastName { get; set; }

    [Column("active")]
    public bool Active { get; set; }
}

我没有此类的viewmodel,它只会用于在我的应用程序中的其他视图模型中填充SelectLists(通过存储库)。但是,我想创建一个这样的属性,以连接SelectLists /下拉列表的名字和姓氏:

    private string _EmployeeName;
    public string EmployeeName
    {
        get
        {
            return _EmployeeName;
        }
        set
        {
            _EmployeeName = this.FirstName + " " + this.LastName;
        }
    }

当我将EmployeeName放入Employee模型时,我收到一条错误,即EmployeeName列不存在。好的,有道理,因为这是我的模型,他们不是这样的专栏。

以下是使用SelectList的一个viewmodel的缩写示例:

public class EquipmentViewModel
{
    [Display(Name = "Equipment ID:")]
    public string EquipmentId { get; set; }

    [Required(ErrorMessage = "Equipment name is required.")]
    [Display(Name = "Equipment Name:")]
    [MaxLength(128)]
    public string EquipmentName { get; set; }

    public SelectList EmployeeList { get; set; }
}

在我的控制器中,我这样做:

var emp = iEmployeeRepository.FindBy(x => x.Active == true).OrderBy(x => x.FirstName);
var equipmentViewModel = new EquipmentViewModel
{
    EquipmentId = e.EquipmentId,
    EquipmentName = e.EquipmentName,
    OriginatorEmployeeId = e.OriginatorEmployeeId,
    EmployeeList = new SelectList(emp, "EmployeeId", "FirstName"),
};
return View(equipmentViewModel);

由于我没有Employee类的viewmodel,我在哪里可以将这个EmployeeName属性替换为FirstName?如果有人能指出我正确的方向,我将不胜感激。

1 个答案:

答案 0 :(得分:2)

您不需要EmployeeName属性。在您的控制器中执行此操作:

var emp = iEmployeeRepository.FindBy(x => x.Active == true)
                             .OrderBy(x => x.FirstName)
                             .Select(x => new { EmployeeId = x.EmployeeId, EmployeeName = x.FristName + " " + x.LastName });
var equipmentViewModel = new EquipmentViewModel
{
    EquipmentId = e.EquipmentId,
    EquipmentName = e.EquipmentName,
    OriginatorEmployeeId = e.OriginatorEmployeeId,
    EmployeeList = new SelectList(emp, "EmployeeId", "EmployeeName"),
};
return View(equipmentViewModel);