Asp.net mvc 在viewmodels中填充SelectList
我有一个由以下模型表示的旧表:Asp.net mvc 在viewmodels中填充SelectList,asp.net-mvc,viewmodel,selectlist,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
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,它将仅用于填充我应用程序中其他viewmodel中的SelectList(通过存储库)。但是,我想创建一个类似这样的属性,以连接SelectList/下拉列表的名字和姓氏:
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?如果有人能给我指出正确的方向,我将不胜感激。你不需要员工姓名财产。在控制器中执行此操作:
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);
好极了!我从没想过。我想我把事情弄得太复杂了。谢谢