1

Name and ID are stored in database. I want to display all name and ID from database to ViewPage Dropdown. Here I displayed Name column only in drop down. Is there possible to display two columns in single drropdown?? Please let me know the solution. Thank You!

Below code write in controller:

    var Employe = (from table in dc.tbl_EmployeeDetails
                           select table.Employee_Name).ToList();
    ViewData["empName"] = Employe ;

var department = (from table in dc.tbl_EmployeeDetails
                                      select table.Department).ToList();

                    ViewData["dept"] = department;

Clientside code(ViewPage):-

<select id="reportto" disabled="disabled" font-size:14px">
    @foreach(var person in ViewData["empName"] as List<string>)
                                            {
                                                if(@Model.employee!=@person)
                                                {
                                                    <option>@person</option>
                                                }
                                            }
 </select>

Here I have displayed Name only in dropdown. How to display both name and department in single dropdown?

Param
  • 77
  • 1
  • 2
  • 9
  • Query the db table, convert the data to a list of `SelectListItem` and use the `DropDownListFor` helper method to render the dropdown. Here is a sample to start with [What is the best ways to bind @Html.DropDownListFor in ASP.NET MVC5?](http://stackoverflow.com/questions/39550804/what-is-the-best-ways-to-bind-html-dropdownlistfor-in-asp-net-mvc5/39550859#39550859) – Shyju Oct 25 '16 at 14:51
  • @Shyju- Once again go through my question. Your link not related to my question. – Param Oct 26 '16 at 05:46

1 Answers1

1

You can concatenate employee name and department name in your SELECT.

var Employe = (from table in dc.tbl_EmployeeDetails
                       select table.Employee_Name + " "+ table.Department).ToList();
ViewData["empName"] = Employe ;

Few suggestions for improvement in your code

I see you are looping through the items and building the options manually. Why not use the html helper methods ?

You can concatenate employee name and department name in your SELECT.

var employeeList= dc.tbl_EmployeeDetails
                     .Select(x=>new SelectListItem { Value=x.Employee_Name,
                                    Text=x.Employee_Name + " "+ x.Department}).ToList();
ViewData["employeeList"] = employeeList;

Now in your view, use the Html.DropDownList helper method

@Html.DropDownList("SelectedEmployee",ViewData["employeeList"] as List<SelectListItem>)

This will generate a SELECT element with name "SelectedEmployee"

Shyju
  • 214,206
  • 104
  • 411
  • 497