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

时间:2019-01-07 13:56:21

标签: c# linq selectlistitem

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

1 个答案:

答案 0 :(得分:2)

您可以生成一个新集合,在其中将两个属性串联在一起,然后构造一个SelectList,例如:

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

编辑:

根据已编辑的问题,您需要生成两个集合,然后进行串联:

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

然后创建一个SelectList并放入ViewBag

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

并在视图中:

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