James123
James123

Reputation: 11652

Concatenate two columns in drop down list in MVC4

I have 3 columns in table (see below) and want concatenate 2 and 3 column as text and column 1 as value. How can we do that in MVC dropdown?

Category Table

ID    CategoryName CategoryName_En
 1    abc           ABC
 2    xyz           XYZ
 3    efg           EFG

dropdown list needs to be looks like

dropdownlist Text     value     
             abc/ABC   1
             xyz/XYZ   2
             efg/EFG   3

Upvotes: 0

Views: 1544

Answers (2)

Moe Bataineh
Moe Bataineh

Reputation: 1080

Something along the lines of this should work:

Categories.Select(i => 
          new SelectListItem 
          { 
               Text = i.CategoryName + "/" + i.CategoryName_En, 
               Value = i.ID 
          }).ToList();

Upvotes: 2

Yogiraj
Yogiraj

Reputation: 1982

It could be as below:

 public IEnumerable<SelectListItem> GetCategoryList(int selectedCatId)
 {     
   // Assuming that GetCategoriesFromDB is returning IEnumerable of Category 
    return GetCategoriesFromDB() 
                       .Select(cat => 
                           SelectListItem
                           {
                               Text = cat.CategoryName + "/" + cat.CategoryName_En,
                               Value = cat.ID,
                               Selected = selectedCatId == cat.ID  
                           }).ToList();
 }

You can just use this method and send the selected category id to it to make sure the correct item is selected.

Upvotes: 3

Related Questions