Distinct Column in SelectList for dropdown list

和自甴很熟 提交于 2021-01-29 11:29:35

问题


I am retrieving distinct values from a table against only one column. when I debug ViewData in controller it has retrieved the values perfectly, but in my view it says Object is not referenced. can some one help me out.

I think the dataValueField and dataTextField are not named "TeamName" anymore after distinct is applied. how to name selected column of my choice so that below SelectList could work. thanks

Controller

ViewData["TeamNames"] = new SelectList(_context.ActivityMaps.Select(s => s.TeamName).Distinct(), "TeamName", "TeamName", model.TeamName);

View

<select asp-for="TeamName" class="form-control" asp-items="ViewBag.TeamNames"></select>

回答1:


Assuming TeamName is string type.

_context.ActivityMaps.Select(s => s.TeamName).Distinct().ToList()

So the above query just return a list of string, and it doesn't have TeamName property.

Just remove the dataValueField and dataTextField.

ViewData["TeamNames"] = new SelectList(_context.ActivityMaps.Select(s => s.TeamName).Distinct().ToList(), model.TeamName);

Update:

var names = _db.ActivityMaps.Select(s => s.TeamName).Distinct().Select(n => new { TeamName = n }).ToList();

ViewData["TeamNames"] = new SelectList(names, "TeamName", "TeamName", model.TeamName);


来源:https://stackoverflow.com/questions/64798230/distinct-column-in-selectlist-for-dropdown-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!