數據庫表:做一個DropDownList鮮明
|ID| |Athlete| |Sport|
1 Jacoby Ellsbury Baseball
2 Dustin Pedroia Baseball
3 Kobe Bryant Basketball
4 Lebron James Basketball
5 Patrick Kane Hockey
6 Sidney Crosby Hockey
我想在我的創建行動只創建Sport
財產的下拉列表
我曾嘗試:
ViewBag.Sport = new SelectList(db.AthleteTable.Distinct(), "ID", "Sport");
或者:
ViewBag.Sport = new SelectList(db.AthleteTable, "ID", "Sport").Distinct();
CSHTML:
<div class="form-group">
@Html.LabelFor(model => model.Sport, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("Sport", null, "-- Select Sport --", htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Sport, "", new { @class = "text-danger" })
</div>
</div>
這使得我的下拉列表,但值重複這樣:
Baseball
Baseball
Basketball
Basketball
Hockey
Hockey
我想要什麼:
Baseball
Basketball
Hockey
任何幫助表示讚賞。
UPDATE:
爲什麼我的表是這樣的原因是因爲我可以通過運動,像這樣創建其他dropdownlists和分隔每個運動員:
List<SelectListItem> lstAthletes = new List<SelectListItem>();
using(var context = new ConnectionString())
{
List<AthleteTable> lstAthletes = context.AthleteTable.ToList();
var groups = lstAthletes.GroupBy(x => x.Sport);
foreach(var group in groups)
{
var slg = new SelectListGroup() { Name = group.Key };
foreach(AthleteTable athlete in group)
{
SelectListItem item = new SelectListItem() { Text = athlete.Athlete, Value = athlete.ID.ToString(), Group = slg };
lstAthletes.Add(item);
}
}
}
運動'不是你的數據集中的單獨故事嗎?您可能想要考慮對數據進行非規範化處理,這可能會使這些(可能還有其他任務)變得更清潔。 –