【发布时间】:2018-12-03 15:06:49
【问题描述】:
我正在根据图书的出版日期和关键字搜索参数对图书索引进行排序。我正在使用一个 switch 语句来选择枚举值,这些值会以不同的方式告诉 Action to Order 搜索结果,升序或降序。但是,Orderby 似乎不起作用,但第一个 case 语句确实起作用。无论如何,该程序只会按最新排序。最旧的第一个不起作用。
public IActionResult Index(String SearchString, Classification DateValueSign)
{
var query = from r in _db.Books select r;
if (SearchString != null && SearchString != "")
{
query = query.Where(x => x.Title.Contains(SearchString) || x.Author.Contains(SearchString) || x.Genre.GenreName.Contains(SearchString));
}
switch (DateValueSign)
{
case Classification.NewestFirst:
query = query.OrderByDescending(x => x.PublicationDate);
break;
case Classification.OldestFirst:
query = query.OrderBy(x => x.PublicationDate);
break;
case Classification.MostPopular:
query = query.OrderByDescending(x => x.AverageRating);
break;
case Classification.LeastPopular:
query = query.OrderBy(x => x.AverageRating);
break;
}
List<Book> SelectedBooks = new List<Book>();
SelectedBooks = query.ToList();
ViewBag.SelectedBooks = SelectedBooks.Count();
ViewBag.TotalBooks = _db.Books.Count();
return View(SelectedBooks);
}
这是索引的视图。快速搜索在索引页面上。
@model IEnumerable<fa18team16BevoBookStore.Models.Book>
@{
ViewData["Title"] = "View";
}
@using fa18team16BevoBookStore.Controllers
<!--This is the quick search box code-->
<form asp-action="Index" asp-controller="Home" method="get">
<p class="form-group">
Search: <input name="SearchString" class="form-control" /><br />
<button type="submit" class="btn btn-secondary">Search</button>
<a asp-action="Index" class="btn btn-danger">Show All</a>
</p>
</form>
<p>Displaying @ViewBag.SelectedBooks out of @ViewBag.TotalBooks </p>
<h2>View</h2>
<div class="form-group">
<label class="radio">@Html.RadioButton("DateValueSign",
Classification.NewestFirst)Newest First</label>
<label class="radio">@Html.RadioButton("DateValueSign",
Classification.OldestFirst)Oldest First</label>
<label class="radio">@Html.RadioButton("DateValueSign",
Classification.MostPopular)Most Popular</label>
<label class="radio">@Html.RadioButton("DateValueSign",
Classification.LeastPopular)Least Popular</label>
</div>
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.UniqueID)
</th>
<th>
@Html.DisplayNameFor(model => model.Title)
</th>
<th>
@Html.DisplayNameFor(model => model.Author)
</th>
<th>
@Html.DisplayNameFor(model => model.Description)
</th>
<th>
@Html.DisplayNameFor(model => model.BookQuantity)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.UniqueID)
</td>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.Author)
</td>
<td>
@Html.DisplayFor(modelItem => item.Description)
</td>
<td>
@Html.DisplayFor(modelItem => item.BookQuantity)
</td>
<td>
<a asp-action="Details" asp-route-
id="@item.BookID">Details</a>
</td>
</tr>
}
</tbody>
</table>
【问题讨论】:
-
添加断点和/或记录以查看进入控制器时的值。可能是枚举未分配但默认。
标签: c# asp.net-core-mvc