动态下拉菜单中的多个选项

时间:2018-11-20 17:57:36

标签: c# asp.net-core-mvc

使用ViewData作为下拉列表时具有多个选项的最佳方法是什么?像这样的enter image description here

我正在使用:  ViewData["LocationId"] = new SelectList(_context.Location, "LocationId", "Address", employees.LocationId); ,它仅显示地址,但我需要: 市 地址 市,州,邮政

在前端,我这样称呼它: <select asp-for="LocationId" asp-items="ViewBag.LocationId">

这可以使用ViewData和selectList完成吗?

谢谢!

1 个答案:

答案 0 :(得分:2)

只需更改为

ViewBag.LocationId = new SelectList(_context.Location, "LocationId", "Address", employees.LocationId);

或者如果您真的想使用ViewData

@{
    ...
    var items = ViewData["LocationId"] as IEnumerable<Microsoft.AspNetCore.Mvc.Rendering.SelectListItem>;
}

<select asp-for="LocationId" asp-items=@items></select>

我建议阅读 What's the difference between ViewData and ViewBag?

但这并不是真正推荐的填充视图的方法。您应该改用ViewModel,它允许您专门定义视图需求。这是ViewModel的示例:MVC6 Dropdownlist of Countries