For solution of above problem, we are creating one student controller and its index view. We want to display a sort records(i.e. First Name,Last Name or Enrollment date) in index view.
this is a code of Student Controller Index Action:
publicActionResultIndex(string sortOrder){ViewBag.NameSortParm=String.IsNullOrEmpty(sortOrder)?"Name":"";ViewBag.DateSortParm= sortOrder =="Date"?"Date_desc":"Date";var students =from s in db.Student // Student is a table i.e. containing records of studentselect s;switch(sortOrder){case"Name": students = students.OrderByDescending(s => s.FirstName);break;case"Date": students = students.OrderBy(s => s.EnrollmentDate);break;case"Date_desc": students = students.OrderByDescending(s => s.EnrollmentDate);break;default: students = students.OrderBy(s => s.FirstName);break;}returnView(students.ToList());}
In Views\Student\Index.cshtml, We have changed below lines:
<p> @Html.ActionLink("Create New Student Record", "Create") </p><table><tr><th> @Html.ActionLink("First Name", "Index", new { sortOrder = ViewBag.NameSortParm }) </th><th> Last Name </th><th> @Html.ActionLink("Enrollment Date", "Index", new { sortOrder = ViewBag.DateSortParm }) </th><th></th></tr> @foreach (var item in Model) {
Liked By
Write Answer
How to sorting with the entity framework is an ASP.NET MVC Application
Join MindStick Community
You have need login or register for voting of answers or question.
Anupam Mishra
05-Feb-2016In Views\Student\Index.cshtml, We have changed below lines: