简体   繁体   中英

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 . eg 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. eg

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

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" })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM