I have a Device Management Application implemented in C# ASP.NET, and I have implemented the Searching and the Sorting functionality too in my application.
My problem is that I cannot sort my searching results, instead of after clicking on Name (to sort the results by name), it will sort all of the devices and not only the searching results.
In this controller, I show the devices without an owner (with UserID == null)
Here is my Controller:
public ActionResult deviceList(String sortBy, String search)
{
if (Session["userID"] != null)
{
ViewBag.SortNameParameter = String.IsNullOrEmpty(sortBy) ? "Name desc" : "";
ViewBag.SortTypeParameter = sortBy == "Type" ? "Type desc" : "Type";
ViewBag.SortManufacturerParameter = sortBy == "Manufacturer" ? "Manufacturer desc" : "Manufacturer";
var devices = db.devices.AsQueryable();
if (devices.Any(x => x.UserID == null))
{
devices = db.devices.Where(x => x.UserID == null);
switch (sortBy)
{
case "Name desc":
devices = devices.Where(x => x.DName.Contains(search)).OrderByDescending(x => x.DName);
break;
...
default:
devices = devices.Where(x => x.DName.Contains(search)).OrderBy(x => x.DName);
break;
}
return View(devices.ToList());
}
The missing parts are the same sorting by type, manufacturer, etc.
Here is my View:
@using (Html.BeginForm("deviceList", "devices", FormMethod.Get))
{
<label>
<b>Search:</b>
@Html.TextBox("Search")
<input type="submit" value="Search" />
</label>
}
</div>
<table class="table table-striped custab">
<thead>
<tr>
<th align="center">
@Html.ActionLink("Name", "deviceList", new { sortBy = ViewBag.SortNameParameter })
</th>
<th>
@Html.ActionLink("Manufacturer", "deviceList", new { sortBy = ViewBag.SortManufacturerParameter })
</th>
<th>
@Html.ActionLink("Type", "deviceList", new { sortBy = ViewBag.SortTypeParameter })
</th>
<th>
@Html.DisplayNameFor(model => model.DOS)
</th>
<th>
@Html.DisplayNameFor(model => model.DOSVersion)
</th>
<th>
@Html.DisplayNameFor(model => model.DProcessor)
</th>
<th align="center">
@Html.DisplayNameFor(model => model.DRAM)
</th>
<th>
@Html.DisplayNameFor(model => model.user.userName)
</th>
<th>Action</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.DName)
</td>
<td>
@Html.DisplayFor(modelItem => item.DManufacturer)
</td>
<td>
@Html.DisplayFor(modelItem => item.DType)
</td>
<td>
@Html.DisplayFor(modelItem => item.DOS)
</td>
<td>
@Html.DisplayFor(modelItem => item.DOSVersion)
</td>
<td>
@Html.DisplayFor(modelItem => item.DProcessor)
</td>
<td>
@Html.DisplayFor(modelItem => item.DRAM)
</td>
<td>
@Html.DisplayFor(modelItem => item.user.userName)
</td>
The search functionality works great, but after the search result if I click on the Name (to sort), the search parameters from URL disappear and it will sort my whole list instead of the search result.
Please help me find out my fault.