下拉列表的SelectList中的不同列 [英] Distinct Column in SelectList for dropdown list

查看:48
本文介绍了下拉列表的SelectList中的不同列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仅从一列中检索表中的不同值.当我在控制器中调试ViewData时,它已经完美地检索了值,但是在我看来,它说未引用对象.有人可以帮我吗?

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.

我认为dataValueField和dataTextField未命名为"TeamName";在应用了distinct之后.如何命名我选择的所选列,以便在SelectList下可以工作.谢谢

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

控制器

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

查看

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

推荐答案

假设 TeamName 是字符串类型.

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

因此上述查询仅返回一个字符串列表,并且没有 TeamName 属性.

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

只需删除dataValueField和dataTextField.

Just remove the dataValueField and dataTextField.

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

更新:

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

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

这篇关于下拉列表的SelectList中的不同列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆