【问题标题】:How can i combine two object fields in Object List into one DropDown in mvc我如何将对象列表中的两个对象字段合并到 mvc 中的一个下拉列表中
【发布时间】:2019-01-07 13:56:20
【问题描述】:

实际上,我有一个在其中生成 viewbag 的动作。我在 ViewBag 中传递一个对象列表。现在在视图中,我想通过我的 viewbag 对象创建一个下拉列表,我需要两个字段作为组合在 mvc 的下拉列表中。例如我的 ServiceList.field1 ,ServiceList.field2 。我希望将这两个字段组合在下拉列表中。

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

我的观点包含

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

如何组合我的两个字段并分别显示在下拉列表中。 例如

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

【问题讨论】:

    标签: c# linq selectlistitem


    【解决方案1】:

    您可以生成一个新集合,在其中将两个属性连接为一个,然后构造一个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" })
    

    【讨论】:

    • 您正在连接两个字段。但我需要在我的 DropDown 的选项中单独分组的两个字段。编辑我的问题以获得更清晰的解释
    • 投影两个列表并连接它们
    • 那个很奇怪的设计,但更新了答案来展示它是如何完成的
    猜你喜欢
    • 1970-01-01
    • 2018-04-21
    • 2021-11-07
    • 1970-01-01
    • 2016-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-14
    相关资源
    最近更新 更多