如何按字母顺序排序DropDownList项目asp.net

时间:2016-04-08 08:25:52

标签: c# asp.net sorting

我在asp.net中很新。今天我想对下拉列表进行排序。 这是我的编辑控制器:

public ActionResult Edit(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    User user = db.Users.Find(id);
    if (user == null)
    {
        return HttpNotFound();
    }
    ViewBag.DefaultCustomerProjectId = new SelectList(db.CustomerProjects, "Id", "Name", user.DefaultCustomerProjectId);
    ViewBag.DefaultServiceId = new SelectList(db.Services, "Id", "Name", user.DefaultServiceId);
    ViewBag.CustomerId = new SelectList(db.Customers, "Id", "Name", user.CustomerId);
    return View(user);
}

这是我的编辑视图

@model TimeReportingLib.User
@{
    ViewBag.Title = "Edit";
}
<h2>Edit</h2>
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>User</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.Id)
        <div class="form-group">
            @Html.LabelFor(model => model.DefaultServiceId, "DefaultServiceId", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("DefaultServiceId", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.DefaultServiceId, "", new { @class = "text-danger" })
            </div>
        </div>

如何按字母顺序对@ Html.DropDownList进行排序?

1 个答案:

答案 0 :(得分:4)

正如我在评论中所说,您可以使用OrderBy扩展方法:

ViewBag.DefaultServiceId = new SelectList(db.Services.OrderBy(s=>s.Name), "Id", "Name", user.DefaultServiceId);