使DropDownList与众不同

时间:2016-04-15 14:30:18

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

数据库表:

|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

感谢任何帮助。

更新:

我的桌子是这样的原因是因为我可以创建其他下拉列表并将每个运动员分开,如下所示:

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);
                }
            }

        }

1 个答案:

答案 0 :(得分:4)

您可以使用GroupBy

var distinctSports = db.AthleteTable.GroupBy(a => a.Sport).Select(g => g.First());
ViewBag.Sport = new SelectList(distinctSports, "ID", "Sport");

然而,从运动员表中选择运动并将运动员身份识别与运动名称完全无关是很奇怪的,因为运动员身份不是运动员身份

通常你应该在运动员表中有一个Sport - 表和一个外键。然后你可以从中选择,所有的运动都是独一无二的。