Q: How can I display firstname + lastname (or any string literal) in a mvc3 dropdown list but keep mapped/bound associated id when item is selected?
-- Model
public class UserT
{
public int UserTId { get; set; }
public string Username { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
-- Controller
// This is what I have to display as userna开发者_JAVA百科me but want to display as FirstName + LastName
// .: How to I change "Username" to FirstName + LastName but bind it to the selected UserTId ???
ViewBag.ContactUserId = new SelectList(db.UserTs, "UserTId", "Username");
-- View
@Html.DropDownList("ContactUserId", "--Select a contact--")
One possibility would be to add a new, read-only property to your UserT
class which returns the first and last names and then bind to that property:
public class UserT
{
public int UserTId { get; set; }
public string Username { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName {
get { return string.Format("{0} {1}", this.FirstName, this.LastName); }
}
}
ViewBag.ContactUserId = new SelectList(db.UserTs, "UserTId", "FullName");
精彩评论