Tuesday, 26 March 2013

MVC - How to sort items in table

Watch this example online.
In this example I have EF connection to 1 table - called StyleMaster.
Then I created controller that performs all CRUD operations with that table. More details in this post:
http://howtodomssqlcsharpexcelaccess.blogspot.ca/2013/03/mvc-4-simple-crud-entity-framework.html
As a result I have index page which displays all records from my StyleMaster table.  Next step is to add sorting functionality to it.

1. First - modify index method
        public ActionResult Index(string sortBy)
        {
            ViewBag.NameSort = String.IsNullOrEmpty(sortBy) ? "Name desc" : "";
            ViewBag.DescSort = sortBy == "Description" ? "Description desc" : "Description";

            var stylemasters = db.StyleMasters.Include(s => s.GroupMaster).Include(s => s.StyleTypeMaster);

            switch (sortBy)
            {
                case "Name desc":
                    stylemasters = stylemasters.OrderByDescending(s => s.StyleName);
                    break;
                case "Name":
                    stylemasters = stylemasters.OrderBy(s => s.StyleName);
                    break;
                case "Description desc":
                    stylemasters = stylemasters.OrderByDescending(s => s.StyleDescription);
                    break;
                case "Description":
                    stylemasters = stylemasters.OrderBy(s => s.StyleDescription);
                    break;
                default:
                     stylemasters = stylemasters.OrderBy(s => s.StyleName);
                    break;
            }
            return View(stylemasters.ToList());
        }
- method is receiving sortBy parameter.  If sortBy is ascending - it will pass descending to view.
- table has columns: Name and Description - this function will allow to sort by these 2 columns.
- than it will load records from table and sort them as requested.  (if nothing passed - first time - sort by name asc)
2. Now modify table headers - add links to it that will call Index method
<table>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.StyleId)
        </th>
        <th>
            @*@Html.DisplayNameFor(model => model.StyleName)*@
            @Html.ActionLink("Name", "Index", new{ sortBy=ViewBag.NameSort})
        </th>
        <th>
            @*@Html.DisplayNameFor(model => model.StyleDescription)*@
            @Html.ActionLink("Description","Index", new{sortBy = ViewBag.DescSort})
        </th>
        <th>
            @Html.DisplayNameFor(model => model.StyleTypeMaster.TypeName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.GroupMaster.GroupName)
        </th>
        <th></th>
    </tr>

No comments:

Post a Comment