HOW TO SORTING WITH THE ENTITY FRAMEWORK IS AN ASP.NET MVC APPLICATION

Anupam Mishra

Total Post:135

Points:949
Posted by  Anupam Mishra
 475  View(s)
Ratings:
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. Anupam Mishra

    Post:135

    Points:949
    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);
             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

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!