问题
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