Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine two dataTextFields for SelectList Description in asp.net MVC 3 using @Html.DropDownListFor

I am returning some stored contacts to view for DropDownList and I am not able to include multiple dataTextFields on my SelectList.

Currently I have:

@Html.DropDownListFor(model => model.Account.AccountContacts, 
         new SelectList(ViewBag.DDContacts, "Contact.ContactID", "Contact.FirstName"),   
         new { @class = "select", style = "width: 100px;" })

I would like to have:

@Html.DropDownListFor(model => model.Account.AccountContacts, 
        new SelectList(ViewBag.DDContacts, "Contact.ContactID", "Contact.FullName"),         
        new { @class = "select", style = "width: 100px;" })

which combines both FirstName and LastName properties.

UPDATE: I am aware of extending contact property, I was curious was there a streamline way to accomplish this in the View or Controller. I tried the two solutions here to no avail. How can I combine two fields in a SelectList text description?

like image 379
user864675 Avatar asked Apr 05 '12 14:04

user864675


3 Answers

I realize this question has an approved answer, though I don't believe it's what the asker was looking for. I came into this issue and this is how I solved it:

@Html.DropDownListFor(model => model.Account.AccountContacts, 
     new SelectList((from c in ViewBag.DDContacts.ToList() select new {
         ID_Value = c.Contact.ContactID,
         FullName = c.Contact.FirstName + " " + c.Contact.LastName
     }), "ID_Value", "FullName"),   
     new { @class = "select", style = "width: 100px;" })

How this works: We are using linq to select specific data from our list and place it into our new object. This new object will contain only two properties, 'ID_Value' and 'FullName'. Now our DropDownListFor can work with this new object to achieve our desired output.

like image 75
mambrowv Avatar answered Oct 21 '22 10:10

mambrowv


Extend contact

public partial class Contact
{
   private string _nameFull;
   public string NameFull
   { 
      get{return FirstName + " " + LastName;}
   }
}
like image 41
Antarr Byrd Avatar answered Oct 21 '22 09:10

Antarr Byrd


I have done something like this:

Controller:

ViewBag.Regiones = from p in modeloDB.Regiones.ToList() select new {
    Id = p.Id,
    Nombre = p.Codigo + " - " + p.Nombre
};

And in the View I have done it like this:

@Html.DropDownListFor(model => model.Region,
new SelectList(@ViewBag.Regiones, "Id", "Nombre"),
new { @class = "comboBox" })
@Html.ValidationMessageFor(model => model.Region)

It works perfectly for me! I hope it still helps!

like image 27
user3806783 Avatar answered Oct 21 '22 08:10

user3806783