Part 64 Implement sorting in asp net mvc

preview_player
Показать описание
C#, SQL Server, WCF, MVC and ASP .NET video tutorials for beginners

Healthy diet is very important both for the body and mind. If you like Aarvi Kitchen recipes, please support by sharing, subscribing and liking our YouTube channel. Hope you can help.

We want to support bi-directional sorting by Name and Gender columns. Here's the requirement
1. Name & Gender columns must be clickable hyperlinks
2. Clicking on the column headers should sort the data. If the data is not already sorted by the column on which you have clicked, the data should be sorted in ascending order. Clicking again on the same column should sort the data in descending order.
3. By default, the data should be sorted by "Name" in ascending order.

By the end of this video, the output should be as shown below. Notice that "Name" and "Gender" columns are rendered as hyperlinks, which the user can click to sort data.

Step 1: Modify the "Index()" action method in HomeController as shown below.
public ActionResult Index(string searchBy, string search, int? page, string sortBy)
{
ViewBag.NameSort = String.IsNullOrEmpty(sortBy) ? "Name desc" : "";
ViewBag.GenderSort = sortBy == "Gender" ? "Gender desc" : "Gender";

var employees = db.Employees.AsQueryable();

if (searchBy == "Gender")
{
employees = employees.Where(x =] x.Gender == search || search == null);
}
else
{
employees = employees.Where(x =] x.Name.StartsWith(search) || search == null);
}

switch (sortBy)
{
case "Name desc":
employees = employees.OrderByDescending(x =] x.Name);
break;
case "Gender desc":
employees = employees.OrderByDescending(x =] x.Gender);
break;
case "Gender":
employees = employees.OrderBy(x =] x.Gender);
break;
default:
employees = employees.OrderBy(x =] x.Name);
break;
}

return View(employees.ToPagedList(page ?? 1, 3));
}

@using PagedList;
@using PagedList.Mvc;

@model PagedList.IPagedList[MVCDemo.Models.Employee]

@{
ViewBag.Title = "Index";
}
[div style="font-family:Arial"]
[h2]Employee List[/h2]
[p]
{
[b]Search By:[/b]
@Html.RadioButton("searchBy", "Name", true) [text]Name[/text]
@Html.RadioButton("searchBy", "Gender") [text]Gender[/text][br /]
@Html.TextBox("search") [input type="submit" value="search" /]

}
[/p]
[table border="1"]
[tr]
[th]
@Html.ActionLink("Name", "Index", new { sortBy = ViewBag.NameSort, searchBy = Request["searchBy"], search = Request["search"] })
[/th]
[th]
@Html.ActionLink("Gender", "Index", new { sortBy = ViewBag.GenderSort, searchBy = Request["searchBy"], search = Request["search"] })
[/th]
[th]
@Html.DisplayNameFor(model =] model.First().Email)
[/th]
[th]Action[/th]
[/tr]
@if (Model.Count() == 0)
{
[tr]
[td colspan="4"]
No records match search criteria
[/td]
[/tr]
}
else
{
foreach (var item in Model)
{
[tr]
[td]
@Html.DisplayFor(modelItem =] item.Name)
[/td]
[td]
@Html.DisplayFor(modelItem =] item.Gender)
[/td]
[td]
@Html.DisplayFor(modelItem =] item.Email)
[/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]
@Html.PagedListPager(Model, page =] Url.Action("Index", new { page, searchBy = Request.QueryString["searchBy"], search = Request.QueryString["search"], sortBy = Request["sortBy"] }), new PagedListRenderOptions() { Display = PagedListDisplayMode.IfNeeded })
[/div]
Рекомендации по теме
Комментарии
Автор

Can you share this project please? The codes you wrote in the description section are very broken.

erenjeagerot
Автор

Great video series! Thank you for sharing you are the best. I hope you continue with that

hsynls
Автор

This article is really very useful.Thank you

thichiphuot
Автор

Great video like always :) clear and explicit
Keep up the good work

dumitrurobert
Автор

Thanks for you effort, just want to point out that the reason you couldn't use where extension method was because that Entity Framework is using deferred execution and it return ObjectSet in ur example. When you use AsQueryable you execute the code and get the result back as IQueryable of employees and then you are able to change the collection.

shahrazkl
Автор

Thank you for your awesome videos!
Is there a way to update the View instead of the Controller so sorting/paging etc. doesn't return to the Controller and re-retrieve the data?

tracylamb
Автор

Hi Suman, these concepts will be covered in detail in our upcoming videos.

Csharp-video-tutorialsBlogspot
Автор

I have some problem with my search functionality. It works properly, but sorting has no effect, albeit sortBy value shows in the URL. After that the sorting refuses to work altogether until I refresh. Fixed it - I forgot to replace the views in if statements.

georgigeorgiev
Автор

i am getting this error : The method 'Skip' is only supported for sorted input in LINQ to Entities.

LalitJindalLonelyStar
Автор

I think it's better to use Kindo UI for Datatable, pagination, sorting ....etc .. it's so complicated to code all of them .

russfry
Автор

Great video,

Could you please tell me how do i use sort in an ActionResult with parameters like that:
[httppost]
ActionResult X(FormCollection f, string sort){...}?

Thanks

akalanata
Автор

For what, you are creating this ViewBugs? An in which moment the value sortBy is filled?

rafalkuc
Автор

Hi Venkat, Can you also please explain of making ajax calls in mvc using jquery retrieving data from database or any wcf Service. Thank you

sumanhappy
Автор

hi venkat
I share this link as much as i possible.
please upload share point video as soon as possible
.

sinraj
Автор

Could you please send the link of the whole course. I subscribed to your channel, but, couldn't find the complete course. Thanks again

amirabdollahi
Автор

I still don't understand how people(developers) could state that MVC is easier than Webforms... I have been following all these courses, I think that these videoseries are by far the top in fact of videocourses, nevertheless, when MVC began, troubles started. I for sure can use it, but, I still think that it is a talkative, left-brained language... Something completely off, for non-expert, and quite a bit hostile, for developer too...

lucasanfilippo