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?
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.
Extend contact
public partial class Contact
{
private string _nameFull;
public string NameFull
{
get{return FirstName + " " + LastName;}
}
}
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With