How to sorting with the entity framework is an ASP.NET MVC Application

Total Post:135

 748  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.
  1. Post:135

    Re: How to sorting with the entity framework is an ASP.NET MVC Application

    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);
          case "Date":
             students = students.OrderBy(s => s.EnrollmentDate);
          case "Date_desc":
             students = students.OrderByDescending(s => s.EnrollmentDate);
             students = students.OrderBy(s => s.FirstName);
       return View(students.ToList());

    In Views\Student\Index.cshtml, We have changed below lines:

        @Html.ActionLink("Create New Student Record", "Create")
                @Html.ActionLink("First Name", "Index", new { sortOrder = ViewBag.NameSortParm })
            <th> Last Name
                @Html.ActionLink("Enrollment Date", "Index", new { sortOrder = ViewBag.DateSortParm })
        @foreach (var item in Model)

      Modified On Apr-11-2018 01:23:16 AM