2017-04-03 64 views
1

在控制器中我有這段代碼,此時我的DropDown列表只是名字。如何在DropDown列表中輸入名字和姓氏

代碼是在這裏:

ViewBag.patnikID = new SelectList(db.tbl_patnici, "pID", "firstname"); 

現在我需要像這樣的代碼:

ViewBag.patnikID = new SelectList(db.tbl_patnici, "pID", ("firstname" + "lastname")); 

怎麼辦呢?

回答

0

你tbl_patn ICI類

public class tbl_patnici 
{ 
    public int pID { get; set; } 
    public string firstname { get; set; } 
    public string lastname { get; set; } 
    //[NotMapped] If you use entityframework then you must use NotMapped attribute. 
    public string fullname { get { return this.firstname + " " + this.lastname; } } 
} 

ViewBag.patnikID = new SelectList(db.tbl_patnici, "pID", "fullname"); 
+1

感謝大家,但@MuratÖNER答案是最適合我。謝謝 –

0

我建議你不要直接綁定到數據庫源,而是綁定到你自己擁有你想要的屬性的IEnumerable。我經常擁有一個具有ID和Text屬性的可重用的「ListItem」類,然後使用一個函數來用我想要的數據填充列表。

例如:

創建一個新類:

public class ListItem 
{ 
    public int ID { get; set; } 
    public string Text { get; set; } 
} 

創建一個輔助函數:

public List<ListItem> GetList() 
{ 
    // get "db" here. 
    return db.tbl_patnici.Select(x => new ListItem { 
     ID = x.pID, 
     Text = x.firstname + " " + x.lastname 
    }); 
} 

說它像這樣:

ViewBag.patnikID = new SelectList(GetList(), "ID", "Text"); 
0

您可以檢查此:

@Html.DropDownListFor(model => model.pID, new SelectList(db.tbl_patnici, "pID", Model.firstname + " " + Model.lastname, Model.pID), new { style = " width:260px" }) 
相關問題