ViewBag.NameSortParm 不起作用

本文关键字:不起作用 NameSortParm ViewBag | 更新日期: 2023-09-27 17:57:03

我有一个国家/地区控制器,它只是处理国家/地区及其相应 ID 的列表。在我的视图页面中,仅显示CountryName列表。

我想通过单击视图页面中的列标题来实现排序,排序顺序为降序,但它不起作用。

这是我的控制器代码:

public ActionResult Index(string sortOrder)
{
    ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
    var countries = from c in db.Countries
                    select c;
    if (ViewBag.NameSortParm == "name_desc")
        countries = countries.OrderByDescending(c => c.CountryName);
    else
        countries = countries.OrderBy(c => c.CountryName);
    return View(db.Countries.ToList());
}

这是我的观点部分:

<h2>List of EU Member States</h2>
<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th>
            @Html.ActionLink("Country Name", "Index", new { sortOrder = ViewBag.NameSortParm })
        </th>
        <th></th>
    </tr>
@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.CountryName)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
            @Html.ActionLink("Details", "Details", new { id=item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ID })
        </td>
    </tr>
}
</table>

Country仅包含 2 列:ID 作为 int 主键和 is_identity = 1,CountryName 作为 varchar(100) 不为空。

我的代码出了什么问题?

ViewBag.NameSortParm 不起作用

您的 Index() 方法从数据库中返回原始值,因为您使用

return View(db.Countries.ToList());

您需要返回排序后的集合

return View(countries.ToList());