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

Go To StackoverFlow.com

11

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?

2012-04-05 14:42
by user864675
Is there a solution to accomplish this within the View or the Controller without modifying the Model? Just curious. Thanks ( I was aware of the option of extending the contacts - user864675 2012-04-05 15:06


24

Extend contact

public partial class Contact
{
   private string _nameFull;
   public string NameFull
   { 
      get{return FirstName + " " + LastName;}
   }
}
2012-04-05 14:55
by Antarr Byrd


10

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.

2013-07-22 16:17
by mambrowv


2

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!

2014-07-07 02:35
by user3806783


1

Go to your Model and create a new Contact class with the same entity name . Be careful when declaring the namespace.
Here's some code that will help ( I hope ) :

public partial class Contact
{ 
   [DataMember]
   public string FullName{ get;set;}
}

In your controller just do something like:

data.FullName =data.Firstname+" "+data.LastName;

That should do it .

2012-04-05 15:01
by Mihai Labo
"Is there a solution to accomplish this within the View or the Controller without modifying the Model? Just curious. Thanks ( I was aware of the option of extending the contacts)" - The extension of the Object does not modify your Model. Just adds a propriety; its your decision if you use it or not. If you really wanna avoid that you can create a Dictionary of all Firstname+Lastname and then use it in your dropdown in the view part. This might help : http://iwantmymvc.com/populate-drop-down-list-mvc- - Mihai Labo 2012-04-05 15:15
Rather do this in the view model like what I showed in my answer. Let the view model take care of this concatenation - Brendan Vogt 2012-04-05 15:51


1

Add a property to your Contact class that returns FullName but takes into account null, empty or whitespace first or last names:

[DataMember]
public string FullName
{
    return string.Join(
        " ",
        new string[] { this.FirstName, this.LastName }
            .Where(s => !string.IsNullOrWhiteSpace(s))));
}
2012-04-05 15:14
by Adrian Thompson Phillips


1

Here is how I would have done it. Just modify the code to fit your scenario. I am changing my code just for demo purposes.

In my view I would have the following:

@model MyProject.ViewModels.MyViewModel

<table>
     <tr>
          <td><b>Bank:</b></td>
          <td>
               @Html.DropDownListFor(
                    x => x.BankId,
                    new SelectList(Model.Banks, "Id", "IdAndName", Model.BankId),
                    "-- Select --"
               )
               @Html.ValidationMessageFor(x => x.BankId)
          </td>
     <tr>
</table>

My view model:

public class MyViewModel
{
     public int BankId { get; set; }
     public IEnumerable<Bank> Banks { get; set; }
}

My bank class:

public class Bank : IEntity
{
     public int Id { get; set; }
     public string Name { get; set; }
     public bool IsActive { get; set; }

     // This property will bring back the concatenated value.
     // If the Id is 1 and Name is My Bank,
     // then the concatenated result would be 1: My Bank
     public string IdAndName
     {
          get
          {
               return (Id.ToString() + ": " + Name);
          }
     }
}

In my controller action:

public ActionResult MyActionMethod()
{
     MyViewModel viewModel = new MyViewModel
     {
          Banks = bankService.GetAll()  // Database call to get all the banks
     };

     return View(viewModel);
}

I hope this helps.

2012-04-05 15:41
by Brendan Vogt


0

Add a property to your Contact class named FullName that simply returns FirstName + " " + LastName.

2012-04-05 14:47
by Keith


0

You can get your contacts from DB as they are... and using LINQ you can query the first collection returning another collection with ID and FULLNAME... then use this collection to populate your dropdownlist.

Thats was just to help your curiosity... I think the best way is to extend your Contact ViewModel for simplicity.

2012-04-05 16:33
by Romias
Ads