数据库表:

|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


任何帮助表示赞赏。

更新:

我的表格之所以如此,是因为我可以创建其他下拉列表并按Sport分隔每个运动员,如下所示:

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

        }

最佳答案

您可以使用GroupBy

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


但是,奇怪的是,您从运动员表中选择了运动,然后将运动员ID映射到运动名称,这是完全不相关的,因为这是运动员ID而非运动ID。

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

关于c# - 使DropDownList与众不同,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36649943/

10-17 02:27