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

8

12

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?

Galumph answered 5/4, 2012 at 14:42 Comment(1)
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)Galumph
B
24

Extend contact

public partial class Contact
{
   private string _nameFull;
   public string NameFull
   { 
      get{return FirstName + " " + LastName;}
   }
}
Butyrin answered 5/4, 2012 at 14:55 Comment(0)
L
11

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.

Lacreshalacrimal answered 22/7, 2013 at 16:17 Comment(0)
A
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!

Aerogram answered 7/7, 2014 at 2:35 Comment(0)
P
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 .

Phonography answered 5/4, 2012 at 15:1 Comment(2)
"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<int,string> of all Firstname+Lastname and then use it in your dropdown in the view part. This might help : iwantmymvc.com/populate-drop-down-list-mvc-3Phonography
Rather do this in the view model like what I showed in my answer. Let the view model take care of this concatenation.Ubangishari
F
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))));
}
Furness answered 5/4, 2012 at 15:14 Comment(0)
U
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.

Ubangishari answered 5/4, 2012 at 15:41 Comment(0)
A
0

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

Arrogate answered 5/4, 2012 at 14:47 Comment(0)
M
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.

Metallo answered 5/4, 2012 at 16:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.