Search code examples
c#linqselectlistitem

How can i combine two object fields in Object List into one DropDown in mvc


Actually i have a action which generates a viewbag in it . i am passing an object List in my ViewBag . Now in the View i want to create a dropdown through my viewbag object which i need two fields as a combined in dropdown List in mvc . e.g. my ServiceList.field1 ,ServiceList.field2 . i want both these fields combined in dropdown .

public ActionResult Add()
{
List<service> ServiceList = new List<service>();
ServiceList = GetService();
ViewBag.BackUPList = ServiceBackupList; 
return View();
}

and my view contains

@Html.DropDownList("name", (SelectList)ViewBag.BackUPList, new { @class = 
"form-control" })

how to combine my both fields and show in dropDown grouped separately. e.g.

ServiceList.field1
ServiceList.field1
ServiceList.field2
ServiceList.field2

Solution

  • You can generate a new collection in which you concatenate two properties in to one and then construct a SelectList like:

    ServiceList = GetService();
    
    var dropDownList = ServiceList.Select(x=> new 
                                            { 
                                               Id = x.IdField, 
                                               Name = x.Field1.ToString() + x.Field2.ToString()
                                          }).ToList();
    ViewBag.BackUPList = new SelectList(dropDownList,"Id","Name");
    

    EDIT:

    As per edited question you need to generate two collection and then concatenate:

    var fieldList = ServiceList.Select(x=> x.IdField1)
                       .Concat(ServiceList.Select(x=> x.IdField2)).ToList();
    

    and then create a SelectList and put in ViewBag :

    ViewBag.BackUPList = fieldList.Select(x => 
                                           new SelectListItem()
                                              { 
                                                Value = x, 
                                                Text = x 
                                          }).ToList();
    

    and in View :

    @Html.DropDownList("name", 
                       ViewBag.BackUPList as IEnumerable<SelectListItem>, 
                       new { @class = "form-control" })