如何在SelectList中加入两个字段?

时间:2012-10-03 10:37:22

标签: c# asp.net-mvc selectlist

所以下面的代码给了一个DropDown框,其中包含来自Drivers的名字列表,但它只是firstnames,我也有姓氏,我该怎么做。我的代码是......

@Html.DropDownListFor(model => model.DriverId, new SelectList(Model.Drivers, "Id", "FirstName", Model.DriverId), "<Select Driver>")
@Html.ValidationMessageFor(model => model.DriverId)


这会选择FirstName,所以说“John”,我希望它是“John Smith”,所以它也包括姓氏。有人可以帮忙吗?
感谢

2 个答案:

答案 0 :(得分:4)

您可以在Drivers模型中创建一个属性:

public string FullName
{
  get
  {
  return firstName + " " + LastName;
  }
}

然后在您的视图中,只需将“FirstName”更改为“FullName”,如下所示:

@Html.DropDownListFor(model => model.DriverId, new SelectList(Model.Drivers, "Id", "FullName", Model.DriverId), "<Select Driver>")

答案 1 :(得分:3)

您可以通过连接FirstName和Surname在您的模型中执行此操作,并在下拉列表中使用

public class DriverViewModel
{
   public string FirstName { get; set; }
   public string Surname { get; set; }
   public string FullName
   {
      get 
      {
         return Surname+" "+FirstName; //String.Format("{0} {1}", Surname, FirstName);
      }
   }
}