Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

write generic method for paging

Tags:

c#

asp.net-mvc

I have controllers where the paging will be calculated. But I have 13 different controllers. So to write that calculation in every controller will be tedious.

this is the comoplete method:

 [Route("sort/{SortColumn}/{SortOrder?}", Name = "Sort-Product")]
        [Route("page/{Page:int}/{SortColumn}/{SortOrder?}", Name = "Paging-Product")]
        [Route("search/{SearchString}")]
        [Route("index")]
        public ActionResult Index(string searchString, string filter, string currentFilter, string sortColumn, string sortOrder, int? page)
        {
            IOrderedQueryable<Product> entities = (IOrderedQueryable<Product>)db.FilteredProducts;

            if (searchString != null) page = 1; else searchString = currentFilter;

            if (filter != null) {
                string[] filters = filter.Split(new char[] { '.' });
                filter = "";

                // filter on form
                if (filters.Length > 0 && !String.IsNullOrEmpty(filters[0])) {
                    FormLibraryEntry formEntry = FormLibraryController.GetFormLibraryEntry(filters[0], StateHelper.GetSchema());

                    if (formEntry != null) {
                        entities = (IOrderedQueryable<Product>)entities.Where(
                            s => s.FormName == formEntry.Id
                        );
                        AddFixedNotification(String.Format(Resources.Entity.Environment.FilteredByFormMessage, formEntry.Name));
                        filter += filters[0];
                    }
                }

                // filter on design template
                if (filters.Length > 1 && !String.IsNullOrEmpty(filters[1])) {
                    var designEntry = DesignTemplateController.GetTemplateLibraryEntry(filters[1], StateHelper.GetSchema());

                    if (designEntry != null) {
                        entities = (IOrderedQueryable<Product>)entities.Where(
                            s => s.TemplateName == designEntry.Id
                        );
                        AddFixedNotification(String.Format(Resources.Entity.Environment.FilteredByDesignTemplateMessage, designEntry.Name));
                        filter += "." + filters[1];
                    }

                }
            }

            if (!String.IsNullOrEmpty(searchString)) {
                entities = (IOrderedQueryable<Product>)entities.Where(
                        s => s.Name.ToUpper().Contains(searchString.ToUpper())
                        || (!String.IsNullOrEmpty(s.FormName) && s.FormName.ToUpper().Contains(searchString.ToUpper()))
                        || (!String.IsNullOrEmpty(s.UrlName) && s.UrlName.ToUpper().Contains(searchString.ToUpper()))
                );
                AddFixedNotification(String.Format(Resources.Entity.Environment.FilteredBySearchTermMessage, searchString));
            }

            switch (sortColumn) {
                case "id":
                    entities = (sortOrder == "desc") ? entities.OrderByDescending(s => s.Id) : entities.OrderBy(s => s.Id);
                    break;
                case "name":
                    entities = (sortOrder == "desc") ? entities.OrderByDescending(s => s.Name) : entities.OrderBy(s => s.Name);
                    break;
                case "enabled":
                    entities = (sortOrder == "desc") ? entities.OrderByDescending(s => s.IsEnabled) : entities.OrderBy(s => s.IsEnabled);
                    break;
                case "formname":
                    entities = (sortOrder == "desc") ? entities.OrderByDescending(s => s.FormName) : entities.OrderBy(s => s.FormName);
                    break;
                case "design":
                    entities = (sortOrder == "desc") ? entities.OrderByDescending(s => s.TemplateName) : entities.OrderBy(s => s.TemplateName);
                    break;
                case "urlname":
                    entities = (sortOrder == "desc") ? entities.OrderByDescending(s => s.UrlName) : entities.OrderBy(s => s.UrlName);
                    break;
                case "forms":
                    entities = (sortOrder == "desc") ? entities.OrderByDescending(s => s.SubmittedForms.Count()) : entities.OrderBy(s => s.SubmittedForms.Count());
                    break;
                case "modified":
                    entities = (sortOrder == "desc") ? entities.OrderByDescending(s => s.ModificationDate) : entities.OrderBy(s => s.ModificationDate);
                    break;
                default:
                    sortColumn = "name";
                    sortOrder = "";
                    entities = (sortOrder == "desc") ? entities.OrderByDescending(s => s.Name) : entities.OrderBy(s => s.Name);
                    break;
            }

            ViewBag.SortColumn = sortColumn;
            ViewBag.SortOrder = sortOrder == "desc" ? "desc" : "";
            ViewBag.SearchString = searchString;
            ViewBag.Filter = filter;

            int pageSize = StateHelper.GetPageSize();
            int pageNumber = StateHelper.HasPageSizeChanged ? 1 : (page ?? 1);


            object selectionProduct = ModelHelper.GetSelectedModelId("Product");
            if (selectionProduct != null) {
                IEnumerable<IEnumerable<Product>> pp = entities.Partition(pageSize);
                int calculatedPage = 0;
                bool found = false;
                foreach (var item in pp) {
                    calculatedPage++;
                    IEnumerable<Product> inner = item as IEnumerable<Product>;
                    foreach (var product in inner) {
                        if (product.Id == (int)selectionProduct) {
                            found = true;
                            ViewBag.selectedRowProduct = product.Id;
                            break;
                        }
                    }
                    if (found)
                        break;
                }
                if (found)
                    pageNumber = calculatedPage;

            }

            return View(entities.ToPagedList(pageNumber, pageSize));
        }

But this is the part of calculation:

object selectionProduct = ModelHelper.GetSelectedModelId("Product");
            if (selectionProduct != null) {
                IEnumerable<IEnumerable<Product>> pp = entities.Partition(pageSize);
                int calculatedPage = 0;
                bool found = false;
                foreach (var item in pp) {
                    calculatedPage++;
                    IEnumerable<Product> inner = item as IEnumerable<Product>;
                    foreach (var product in inner) {
                        if (product.Id == (int)selectionProduct) {
                            found = true;
                            ViewBag.selectedRowProduct = product.Id;
                            break;
                        }
                    }
                    if (found)
                        break;
                }
                if (found)
                    pageNumber = calculatedPage;

            }

So I try to build a helper method like this:

 public static bool FindPage(Type T, object modelId, IEnumerable<Type> entities, int pageSize, int calculatedPage, int? id)
        {
            if (modelId != null) {
                calculatedPage = 0;
                IEnumerable<IEnumerable<T>> pp = entities.Partition(pageSize);
                int page = 0;
                bool found = false;
                foreach (var item in pp) {
                    page++;
                    IEnumerable<Type> inner = item as IEnumerable<Type>;
                    foreach (var product in inner) {
                        if (id == (int)modelId) {
                            found = true;
                            break;
                        }
                    }
                    if (found)
                        break;
                }
                if (found)
                    calculatedPage = page;
                else
                    calculatedPage = 0;

                return found;
            }
            return false;
        }

But I get this error:

The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?) 

Thank you

like image 380
InfinityGoesAround Avatar asked Jul 14 '15 07:07

InfinityGoesAround


1 Answers

Try:

public static bool FindPage<T>(object modelId, IEnumerable<T> entities, int pageSize, int calculatedPage, int? id)
    {
        if (modelId != null) {
            calculatedPage = 0;
            IEnumerable<IEnumerable<T>> pp = entities.Partition(pageSize);
            int page = 0;
            bool found = false;
            foreach (var item in pp) {
                page++;
                IEnumerable<T> inner = item as IEnumerable<T>;
                foreach (var product in inner) {
                    if (id == (int)modelId) {
                        found = true;
                        break;
                    }
                }
                if (found)
                    break;
            }
            if (found)
                calculatedPage = page;
            else
                calculatedPage = 0;

            return found;
        }
        return false;
    }
like image 178
serhiyb Avatar answered Nov 09 '22 06:11

serhiyb