Home > DeveloperSection > Forums > How to sorting with the entity framework is an ASP.NET MVC Application
Anupam Mishra

Total Post:135

Points:949
Posted on    February-05-2016 10:24 PM

 ASP.Net C#  ASP.Net  ASP.NET MVC 
Ratings:


 1 Reply(s)
 248  View(s)
Rate this:
Hello Everyone,
I want to know how to sort record with the using of entity framework in ASP.NET MVC. Can anyone give me a solution with example.

Thank you.


Anupam Mishra

Total Post:135

Points:949
Posted on    February-05-2016 10:56 PM

Finally, I have solve this problem.
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:
public ActionResult Index(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 student
                  select 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;
   }
   return View(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)
    {

Modified On Feb-06-2016 03:43:01 AM

Don't want to miss updates? Please click the below button!

Follow MindStick