我有以下表格标题,实际上是一个ActionLink:
<th>
@Html.ActionLink("Country Name", "Index", new { sortOrder = "CountryName", CurrentSort = ViewBag.CurrentSort })
</th>
我想要做的是,每当我点击此ActionLink时,sortOrder
值将更改为""
(空字符串)。如果我再次点击ActionLink,sortorder
值将更改回"CountryName"
。这意味着,onclick事件将像sortOrder
值的切换一样。
我怎样才能做到这一点?
请注意,我将在控制器方法中使用sortOrder
值。这是控制器方法的代码:
public ActionResult Index(string sortOrder, string CurrentSort, int? page)
{
int pageSize = 10;
int pageIndex = 1;
pageIndex = page.HasValue ? Convert.ToInt32(page) : 1;
ViewBag.CurrentSort = sortOrder;
sortOrder = String.IsNullOrEmpty(sortOrder) ? "CountryName" : sortOrder;
IPagedList<Country> countries = null;
if (sortOrder.Equals(CurrentSort))
{
countries = db.Countries.OrderByDescending(c => c.CountryName).ToPagedList(pageIndex, pageSize);
}
else
{
countries = db.Countries.OrderBy(c => c.CountryName).ToPagedList(pageIndex, pageSize);
}
return View(countries);
}
答案 0 :(得分:0)
ViewBag
只会从操作持续到View,之后它将无法使用,因此如果在Index之后调用其他一些操作,您将丢失作为SortOrder发送的最后一个值。
解决方案可以是使用TempData
,它也可以在操作和多个请求之间保留:
更改您的操作代码以使用TempData
:
TempData["CurrentSort"] = sortOrder;
sortOrder = String.IsNullOrEmpty(sortOrder) ? "CountryName" : sortOrder;
现在在视图中使用TempData.Peek()
来读取值,以便在TempData
中保留值以便再次阅读:
@Html.ActionLink("Country Name",
"Index",
new
{
sortOrder = "CountryName",
CurrentSort = TempData.Peek("CurrentSort") as String
}
)
你完成了行动:
public ActionResult Index(string sortOrder, string CurrentSort, int? page)
{
int pageSize = 10;
int pageIndex = 1;
pageIndex = page.HasValue ? Convert.ToInt32(page) : 1;
sortOrder = String.IsNullOrEmpty(CurrentSort) ? "CountryName" : CurrentSort;
// toggling sort
TempData["CurrentSort"] = sortOrder;
// persisting selected Sort
IPagedList<Country> countries = null;
if (sortOrder.Equals(CurrentSort))
{
countries = db.Countries.OrderByDescending(c => c.CountryName).ToPagedList(pageIndex, pageSize);
}
else
{
countries = db.Countries.OrderBy(c => c.CountryName).ToPagedList(pageIndex, pageSize);
}
return View(countries);
}
您可以阅读有关TempData的this article,也可以阅读ViewData,ViewBag and TempData in asp.net mvc