开发者

How to display a custom string in mvc3 dropdownlist but keep id field mapped to item selected?

开发者 https://www.devze.com 2023-04-10 15:02 出处:网络
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?

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");
0

精彩评论

暂无评论...
验证码 换一张
取 消