// GET: ProductController
        public async Task <ActionResult> Index(int page = 1)
        {
            int pageSize = 3;               // количество элементов на странице

            var products = await _productService.GetAllAsync();

            foreach (var item in products)
            {
                var category = await _categoryService.GetAsync(item.CategoryId);

                item.Category.Name = category?.Name;
            }
            var count = products.Count();
            var items = products.Skip((page - 1) * pageSize).Take(pageSize);

            PageViewModel         pageViewModel = new PageViewModel(count, page, pageSize);
            ProductIndexViewModel viewModel     = new ProductIndexViewModel
            {
                PageViewModel = pageViewModel,
                Products      = items
            };

            return(View(viewModel));
        }
Example #2
0
        // GET: Product
        public ActionResult Index(int id, string sort)
        {
            var model = new ProductIndexViewModel();

            using (var db = new MyDbContext())
            {
                model.CategoryName = string.Join("", db.Categories.Where(x => x.CategoryId == id).Select(x => x.Name));
                model.CategoryId   = id;
                model.ProductList.AddRange(db.Products
                                           .Select(x => new ProductIndexViewModel.ProductListViewModel
                {
                    ProductId   = x.ProductId,
                    Name        = x.Name,
                    Description = x.Description,
                    Price       = x.Price,
                    PhotoByte   = x.Photo,
                    CategoryId  = x.CategoryId
                }).Where(x => x.CategoryId == id));

                model = Sort(model, sort);

                return(View(model));
            }
        }
        public async Task <IActionResult> Index(
            string sortOrder,
            string category,
            string brand,
            string searchString,
            decimal?curMinPrice,
            decimal?curMaxPrice,
            int?pageNumber,
            int?pageSize)
        {
            // Use LINQ to get list of genres.
            IQueryable <string> categoryQuery = from p in _context.Products
                                                orderby p.Category
                                                select p.Category;

            var products = from p in _context.Products
                           select p;

            if (!string.IsNullOrEmpty(searchString))
            {
                products = products.Where(p => p.Name.Contains(searchString) ||
                                          p.Brand.Contains(searchString));
            }

            if (!string.IsNullOrEmpty(category))
            {
                products = products.Where(x => x.Category == category);
            }

            var filteredProducts = products;

            if (!string.IsNullOrEmpty(brand))
            {
                products = products.Where(p => p.Brand.Equals(brand));
            }

            var     brandFilteredProducts = products;
            decimal?minPrice = 0, maxPrice = 0;

            if (brandFilteredProducts.Any())
            {
                minPrice = await brandFilteredProducts.MinAsync(p => p.Price);

                maxPrice = await brandFilteredProducts.MaxAsync(p => p.Price);
            }

            if (curMinPrice != null)
            {
                products = products.Where(p => p.Price >= curMinPrice);
            }
            else
            {
                curMinPrice = await brandFilteredProducts.MinAsync(p => p.Price);
            }

            if (curMaxPrice != null)
            {
                products = products.Where(p => p.Price <= curMaxPrice);
            }
            else
            {
                curMaxPrice = await brandFilteredProducts.MaxAsync(p => p.Price);
            }


            ViewData["NameSortParm"]  = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
            ViewData["PriceSortParm"] = sortOrder == "price_asc" ? "price_desc" : "price_asc";
            IOrderedQueryable <Product> orderedProductsQuery;

            switch (sortOrder)
            {
            case "name_desc":
                orderedProductsQuery = products.OrderByDescending(s => s.Name);
                break;

            case "price_asc":
                orderedProductsQuery = products.OrderBy(s => s.Price);
                break;

            case "price_desc":
                orderedProductsQuery = products.OrderByDescending(s => s.Price);
                break;

            default:
                orderedProductsQuery = products.OrderBy(s => s.Name);
                break;
            }

            var cart = SessionHelper
                       .GetObjectFromJson <List <ProductItem> >(HttpContext.Session, "cart");

            var paginatedProducts = await PagingList
                                    .CreateAsync(orderedProductsQuery,
                                                 pageSize ?? 6,
                                                 pageNumber ?? 1);

            paginatedProducts.Action     = nameof(Index);
            paginatedProducts.RouteValue = new RouteValueDictionary
            {
                { "sortOrder", sortOrder },
                { "searchString", searchString },
                { "pageSize", pageSize },
            };

            //Add Photo to product
            List <Product> finalFilteredProducts = new List <Product>();

            foreach (Product tempProduct in filteredProducts)
            {
                var product = await _context.Products.Include(p => p.Photos).FirstOrDefaultAsync(p => p.ID == tempProduct.ID);

                finalFilteredProducts.Add(product);
            }
            var model = new ProductIndexViewModel()
            {
                ProductsAllFiltered = finalFilteredProducts,
                PaginatedProducts   = paginatedProducts,
                Category            = category,
                SearchString        = searchString,
                SortOrder           = sortOrder,
                Brand       = brand,
                CurMinPrice = curMinPrice,
                CurMaxPrice = curMaxPrice,
                MinPrice    = minPrice ?? 0,
                MaxPrice    = maxPrice ?? 0,
                PageSize    = pageSize ?? 6,
                Categories  = await categoryQuery.Distinct().ToListAsync(),
                Cart        = cart
            };

            ViewBag.returnUrl = HttpContext.Request.Path + HttpContext.Request.QueryString;
            var errorList = TempData.Get <List <string> >("Error");

            if (errorList != null)
            {
                foreach (var error in errorList)
                {
                    ModelState.AddModelError("", error);
                }
            }
            return(View(model));
        }
Example #4
0
        // GET: Products
        public async Task <IActionResult> Index(string searchString, string animalType, string productType)
        {
            if (!GetAuthorization(4, 'r'))
            {
                return(NotFound());
            }
            ViewBag.Permission = getPermissions();
            var query = from product in _context.Products
                        join productsType in _context.ProductTypes on product.ProductTypeFK equals productsType.ProductTypeID
                        join animalsType in _context.AnimalTypes on product.AnimalTypeFK equals animalsType.AnimalTypeID
                        select new
            {
                ProductID       = product.ProductID,
                Name            = product.Name,
                Quantity        = product.Quantity,
                WeekStock       = product.WeekStock,
                MonthStock      = product.MonthStock,
                AnimalTypeFK    = product.AnimalTypeFK,
                ProductTypeFK   = product.ProductTypeFK,
                ProductTypeName = productsType.Name,
                AnimaltypeName  = animalsType.Name
            };

            if (!String.IsNullOrEmpty(searchString))
            {
                query = query.Where(product => product.Name.Contains(searchString));
            }

            if (!String.IsNullOrEmpty(animalType))
            {
                query = query.Where(product => product.AnimaltypeName.Contains(animalType));
            }

            if (!String.IsNullOrEmpty(productType))
            {
                query = query.Where(product => product.ProductTypeName.Contains(productType));
            }

            var result = query.ToList().Select(e => new Product
            {
                ProductID       = e.ProductID,
                Name            = e.Name,
                Quantity        = e.Quantity,
                WeekStock       = e.WeekStock,
                MonthStock      = e.MonthStock,
                ProductTypeName = e.ProductTypeName,
                AnimaltypeName  = e.AnimaltypeName
            }).ToList();


            var animalTypeQuery = from animal in _context.AnimalTypes
                                  orderby animal.Name
                                  select animal.Name;

            var productTypeQuery = from product in _context.ProductTypes
                                   orderby product.Name
                                   select product.Name;

            var productIndexVM = new ProductIndexViewModel
            {
                Products     = result,
                AnimalTypes  = new SelectList(animalTypeQuery.Distinct().ToList()),
                ProductTypes = new SelectList(productTypeQuery.Distinct().ToList())
            };

            return(View(productIndexVM));
        }
Example #6
0
        // GET: Products
        public ActionResult Index(string category, string search, string sortBy, int?page)
        {
            //instantiate a new view model
            var viewModel = new ProductIndexViewModel();

            //select the products
            var products = db.Products.Include(p => p.Category);

            //perform the search and save the search string to the viewModel
            if (!String.IsNullOrEmpty(search))
            {
                products = products.Where(p => p.Name.Contains(search) ||
                                          p.Description.Contains(search) ||
                                          p.Category.Name.Contains(search));
                viewModel.Search = search;
            }

            //group search results into categories and count how many items in each category
            viewModel.CatsWithCount = from matchingProducts in products
                                      where
                                      matchingProducts.CategoryID != null
                                      group matchingProducts by
                                      matchingProducts.Category.Name into
                                      catGroup
                                      select new CategoryWithCount()
            {
                CategoryName = catGroup.Key,
                ProductCount = catGroup.Count()
            };


            if (!String.IsNullOrEmpty(category))
            {
                products           = products.Where(p => p.Category.Name == category);
                viewModel.Category = category;
            }


            //sort the results
            switch (sortBy)
            {
            case "price_lowest":
                products = products.OrderBy(p => p.Price);
                break;

            case "price_highest":
                products = products.OrderByDescending(p => p.Price);
                break;

            default:
                products = products.OrderBy(p => p.Name);
                break;
            }

            const int PageItems   = 3;
            int       currentPage = (page ?? 1);

            viewModel.Products = products.ToPagedList(currentPage, PageItems);
            viewModel.SortBy   = sortBy;
            viewModel.Sorts    = new Dictionary <string, string>
            {
                { "Price low to high", "price_lowest" },
                { "Price high to low", "price_highest" }
            };

            return(View(viewModel));
        }
        private IEnumerable <Product> GetSortedProductList(IEnumerable <Product> productSearchResult, bool isDesc, string col, ref ProductIndexViewModel viewModel)
        {
            viewModel.IsDescCompany     = false;
            viewModel.IsDescPrice       = false;
            viewModel.IsDescSubCategory = false;
            viewModel.IsDescTitle       = false;
            viewModel.IsDescId          = false;
            viewModel.SelectedColumn    = col;
            viewModel.IsDesc            = isDesc;

            if (isDesc && col == "title")
            {
                productSearchResult = productSearchResult.OrderByDescending(prod => prod.Title);
            }
            else if (!isDesc && col == "title")
            {
                productSearchResult   = productSearchResult.OrderBy(prod => prod.Title);
                viewModel.IsDescTitle = true;
            }
            else if (isDesc && col == "company")
            {
                productSearchResult = productSearchResult.OrderByDescending(prod => prod.Company.Title);
            }
            else if (!isDesc && col == "company")
            {
                productSearchResult     = productSearchResult.OrderBy(prod => prod.Company.Title);
                viewModel.IsDescCompany = true;
            }
            else if (isDesc && col == "id")
            {
                productSearchResult = productSearchResult.OrderByDescending(prod => prod.Id);
            }
            else if (!isDesc && col == "id")
            {
                productSearchResult = productSearchResult.OrderBy(prod => prod.Id);
                viewModel.IsDescId  = true;
            }
            else if (isDesc && col == "subCategory")
            {
                productSearchResult = productSearchResult.OrderByDescending(prod => prod.SubCategory.Title);
            }
            else if (!isDesc && col == "subCategory")
            {
                productSearchResult         = productSearchResult.OrderBy(prod => prod.SubCategory.Title);
                viewModel.IsDescSubCategory = true;
            }
            else if (isDesc && col == "price")
            {
                productSearchResult = productSearchResult.OrderByDescending(prod => prod.Price);
            }
            else if (!isDesc && col == "price")
            {
                productSearchResult   = productSearchResult.OrderBy(prod => prod.Price);
                viewModel.IsDescPrice = true;
            }

            return(productSearchResult);
        }
        public ActionResult ProductsOnSale(string category, string search, string order, int?size, int?page)
        {
            // instantiate a new view model
            ProductIndexViewModel viewModel = new ProductIndexViewModel();

            // select the products
            var products = db.Products.Include(p => p.Category).Where(p => p.OnSale == true);

            // perform the search and save the search string to the viewModel
            if (!String.IsNullOrEmpty(search))
            {
                products = products.Where(p => p.ProductName.Contains(search) ||
                                          p.Description.Contains(search) ||
                                          p.Category.CategoryName.Contains(search));
                viewModel.search = search;
            }

            // group search results into categories and count how many items in each category
            viewModel.CatsWithCount = from matchingProducts in products
                                      orderby matchingProducts.Category.CategoryName
                                      group matchingProducts by
                                      matchingProducts.Category.CategoryName into
                                      catGroup
                                      select new CategoryWithCount()
            {
                CategoryName = catGroup.Key,
                ProductCount = catGroup.Count()
            };

            if (!String.IsNullOrEmpty(category))
            {
                products           = products.Where(p => p.Category.Path == category);
                viewModel.category = category;
            }

            // sort the results
            switch (order)
            {
            case "price":
                products = products.OrderBy(p => p.Price);
                break;

            case "price-desc":
                products = products.OrderByDescending(p => p.Price);
                break;

            default:
                products = products.OrderByDescending(p => p.SaleEnd);
                break;
            }

            int currentPage = (page ?? 1);

            viewModel.size     = size;
            viewModel.Products = products.ToPagedList(currentPage, size ?? Constants.PageItems);
            viewModel.order    = order;
            viewModel.filters  = new Dictionary <string, string>
            {
                { "Low to high", "price" },
                { "High to low", "price-desc" }
            };
            return(View(viewModel));
        }
Example #9
0
        public ActionResult Index(string category, string search, string sortBy, int?page)
        {
            ProductIndexViewModel vm = new ProductIndexViewModel();

            var products = db.Products.Include(p => p.Category);


            //if the passed search phrase variable value is not equal to null then
            //the products variable declared above will be instantiated with db product table data that has been filtered to get values that are relevant to the searchPhrase .
            if (!String.IsNullOrEmpty(search))
            {
                products = products.Where(p => p.ProductName.Contains(search) ||
                                          p.ProductDescription.Contains(search) ||
                                          p.Category.CategoryName.Contains(search));
                vm.Search = search;
            }

            vm.CatsWithCount = from matchingProducts in products
                               where
                               matchingProducts.CategoryID != null
                               group matchingProducts by
                               matchingProducts.Category.CategoryName into
                               catGroup
                               select new CategoryWithCount()
            {
                CategoryName = catGroup.Key,
                ProductCount = catGroup.Count()
            };

            //if the passed category choice variable value is not equal to null then
            //the products variable declared above will be instantiated with db product table data that has been filtered through query to get values relating to the category value.
            if (!String.IsNullOrEmpty(category))
            {
                products    = products.Where(p => p.Category.CategoryName == category);
                vm.Category = category;
            }

            //sort the results
            switch (sortBy)
            {
            case "price_lowest":
                products = products.OrderBy(p => p.ProductPrice);
                break;

            case "price_highest":
                products = products.OrderByDescending(p => p.ProductPrice);
                break;

            default:
                products = products.OrderBy(p => p.ProductName);
                break;
            }

            int currentPage = (page ?? 1);

            vm.Products = products.ToPagedList(currentPage, Constants.PageItems);
            vm.SortBy   = sortBy;
            vm.Sorts    = new Dictionary <string, string>
            {
                { "Price low to high", "price_lowest" },
                { "Price high to low", "price_highest" }
            };



            return(View(vm));
        }
Example #10
0
        // GET: Products
        public ActionResult Index(string category, string search, string sortBy, int?page)
        {
            ProductIndexViewModel viewModel = new ProductIndexViewModel();

            var products = db.Products.Include(p => p.Category);

            if (!String.IsNullOrEmpty(category))
            {
                products = products.Where(p => p.Category.Name == category);
                // viewModel.Category = category;
            }

            if (!String.IsNullOrEmpty(search))
            {
                products         = products.Where(p => p.Name.Contains(search) || p.Description.Contains(search) || p.Category.Name.Contains(search));
                viewModel.search = search;
            }

            viewModel.CatsWithCount = from matchingProducts in products
                                      where
                                      matchingProducts.CategoryID != null
                                      group matchingProducts by
                                      matchingProducts.Category.Name into
                                      catGroup
                                      select new CategoryWithCount()
            {
                CategoryName = catGroup.Key,
                ProductCount = catGroup.Count()
            };

            var categories = products.OrderBy(p => p.Category.Name).Select(p => p.Category.Name).Distinct();

            if (!String.IsNullOrEmpty(category))
            {
                products           = products.Where(p => p.Category.Name == category);
                viewModel.Category = category;
            }

            switch (sortBy)
            {
            case "price_lowest":
                products = products.OrderBy(p => p.Price);
                break;

            case "price_highest":
                products = products.OrderByDescending(p => p.Price);
                break;

            default:
                products = products.OrderBy(p => p.Name);
                break;
            }

            int currentPage = (page ?? 1);

            viewModel.Products = products.ToPagedList(currentPage, Constants.PageItems);
            viewModel.SortBy   = sortBy;
            viewModel.Sorts    = new Dictionary <string, string>
            {
                { "Price low to high", "price_lowest" },
                { "Price high to low", "price_highest" }
            };

            return(View(viewModel));
        }
        public ActionResult Index(string category, string brand, string search, string sortBy, int?page)
        {
            //init new view model
            ProductIndexViewModel viewModel = new ProductIndexViewModel();

            var products = db.Products.Include(p => p.Category);

            /* find product where product name||description||category contains search */

            if (!String.IsNullOrEmpty(search))
            {
                products = products.Where(p => p.Name.Contains(search) ||
                                          p.Description.Contains(search) || p.Category.Name.Contains(search) ||
                                          p.Brand.Name.Contains(search));
                //ViewBag.Search = search;
                viewModel.Search = search;
            }

            // group search results into categories and count items in each category
            viewModel.CatsWithCount = from matchingProducts in products
                                      where matchingProducts.CategoryID != null
                                      group matchingProducts by
                                      matchingProducts.Category.Name into catGroup
                                      select new ProductIndexViewModel.CategoryWithCount()
            {
                CategoryName = catGroup.Key,
                ProductCount = catGroup.Count()
            };

            // group search results into brands and count items in each brand
            viewModel.BrandsWithCount = from matchingProducts in products
                                        where matchingProducts.BrandID != null
                                        group matchingProducts by
                                        matchingProducts.Brand.Name into brandGroup
                                        select new ProductIndexViewModel.BrandWithCount()
            {
                BrandName    = brandGroup.Key,
                ProductCount = brandGroup.Count()
            };

            //var categories = products.OrderBy(p => p.Category.Name).Select(P => P.Category.Name).Distinct();

            if (!String.IsNullOrEmpty(category))
            {
                products           = products.Where(p => p.Category.Name == category);
                viewModel.Category = category;
            }
            if (!String.IsNullOrEmpty(brand))
            {
                products        = products.Where(p => p.Brand.Name == brand);
                viewModel.Brand = brand;
            }
            // sort the results
            switch (sortBy)
            {
            case "price_lowest":
                products = products.OrderBy(p => p.Price);
                break;

            case "price_highest":
                products = products.OrderByDescending(p => p.Price);
                break;

            default:
                products = products.OrderBy(p => p.Name);
                break;
            }


            //const int PageItems = 5;
            int currentPage = (page ?? 1);

            viewModel.Products = products.ToPagedList(currentPage, Constants.PagedItems);

            //ViewBag.Category = new SelectList(categories);
            //viewModel.Products = products;

            viewModel.SortBy = sortBy;


            viewModel.Sorts = new Dictionary <string, string>
            {
                { "Price low to high", "price_lowest" },
                { "Price high to low", "price_highest" }
            };


            //return View(products.ToList());
            return(View(viewModel));
        }
Example #12
0
        // GET: Products
        public ActionResult Index(string category, string search, string sortBy, int?page)
        {
            //instantiate a new view model
            ProductIndexViewModel viewModel = new ProductIndexViewModel();


            // selecciona los productos
            var products = db.Products.Include(p => p.Category);

            if (!String.IsNullOrEmpty(search))
            {
                //filtra los productos por nombre, descripciòn o categorìa
                products = products.Where(p => p.Name.Contains(search) ||
                                          p.Description.Contains(search) ||
                                          p.Category.Name.Contains(search));
                viewModel.Search = search;
            }

            //if (!String.IsNullOrEmpty(category))
            //{
            //    //filtrando los productos por categorias
            //    products = products.Where(p => p.Category.Name == category);
            //}

            // agrupar los resultados de la búsqueda en categorías y contar cuántos elementos en cada categoría
            viewModel.CatsWithCount = from matchingProducts in products
                                      where
                                      matchingProducts.CategoryID != null
                                      group matchingProducts by
                                      matchingProducts.Category.Name into
                                      catGroup
                                      select new CategoryWithCount()
            {
                CategoryName = catGroup.Key,
                ProductCount = catGroup.Count()
            };



            //var categories = products.OrderBy(p => p.Category.Name).Select(p =>
            //                                  p.Category.Name).Distinct();

            if (!String.IsNullOrEmpty(category))
            {
                products           = products.Where(p => p.Category.Name == category);
                viewModel.Category = category;
            }
            //Ordena los resultados desde la url
            switch (sortBy)
            {
            case "mas_bajo":
                products = products.OrderBy(p => p.Price);
                break;

            case "mas_alto":
                products = products.OrderByDescending(p => p.Price);
                break;

            default:
                products = products.OrderBy(p => p.Name);
                break;
            }
            //Esto es para la paginación
            //número de elementos que aparecerán en cada página
            //const int PageItems = 3;

            int currentPage = (page ?? 1);

            // la propiedad de productos del modelo de vista se le asigna una lista de productos PagedList que especifica el
            //página actual y el número de elementos por página con el código
            viewModel.Products = products.ToPagedList(currentPage, Constants.PageItems);
            //Finalmente, el valor sortBy ahora se guarda en el modelo de vista para que el orden de clasificación de la lista de productos sea
            //se conserva al pasar de una página a otra mediante el código:
            viewModel.SortBy = sortBy;
            //este se utiliza para rellenar el ddl de ordenar por precio
            viewModel.Sorts = new Dictionary <string, string>
            {
                { "Precio bajo a alto", "mas_bajo" },
                { "Precio alto a bajo", "mas_alto" }
            };

            return(View(viewModel));
        }
        public ActionResult Index(string category, string search, string sortBy, int?page)
        {
            ProductIndexViewModel viewModel = new ProductIndexViewModel();

            // Eager loading to include all the categories for the products.
            var products = db.Products.Include(p => p.Category);

            // If the search query is not empty, search the product name, description, and category name for the query
            // Also assign the search query to the viewModel for further queries (Category filtering, products count, etc..).
            if (!string.IsNullOrEmpty(search))
            {
                products = products.Where(p =>
                                          p.Category.Name.Contains(search) ||
                                          p.Name.Contains(search) ||
                                          p.Description.Contains(search));
                viewModel.Search = search;
            }

            // After the search query is performed, group each product together with their certain Category as the key.
            // and generate a list to use in the view DropDownList.
            viewModel.CatsWithCount = products
                                      .Where(x => x.CategoryID != null)
                                      .GroupBy(y => y.Category.Name)
                                      .Select(x => new CategoryWithCount()
            {
                CategoryName = x.Key,
                ProductCount = x.Count(),
            });

            // If they category filter is not empty, filter the products by their categories.
            if (!string.IsNullOrEmpty(category))
            {
                products           = products.Where(p => p.Category.Name == category);
                viewModel.Category = category;
            }

            // Apply the sorting filter, or default to the normal because of PagedList.
            switch (sortBy)
            {
            case "price_lowest":
                products = products.OrderBy(p => p.Price);
                break;

            case "price_highest":
                products = products.OrderByDescending(p => p.Price);
                break;

            default:
                products = products.OrderBy(p => p.Name);
                break;
            }

            // Paging the product list.
            int currentPage = (page ?? 1);

            viewModel.Products = products.ToPagedList(currentPage, Constants.ProductPageItems);

            // Maintain the SortBy in the viewModel for further processing.
            viewModel.SortBy = sortBy;

            // The SortBy generated dictionary to use in the view DropDownList.
            viewModel.Sorts = new Dictionary <string, string>
            {
                { "Price low to high", "price_lowest" },
                { "Price high to low", "price_highest" }
            };

            return(View(viewModel));
        }
Example #14
0
        // GET: Product
        public ActionResult Index(int?id, int?categoryId)
        {
            FindAllProductQueryResult  result         = Query.For <FindAllProductQueryResult>().With(new EmptyCriterion());
            FindActiveTableQueryResult tableResult    = Query.For <FindActiveTableQueryResult>().With(new EmptyCriterion());
            FindAllCategoryQueryResult categoryResult = Query.For <FindAllCategoryQueryResult>().With(new EmptyCriterion());

            ProductIndexViewModel vm = new ProductIndexViewModel
            {
                ActiveProducts  = result.ActiveProducts.Select(ToViewModel),
                DeletedProducts = result.DeletedProducts.Select(ToViewModel)
            };

            if (id == null)
            {
                vm.NewProduct = new ProductAddViewModel
                {
                    CategorySelectListItems = categoryResult.ActiveCategories.Select(ToSelectListItem).ToList(),
                    TableSelectListItems    = tableResult.ActiveTables.Select(ToSelectListItem).ToList()
                };

                if (categoryId.HasValue)
                {
                    Category category = categoryResult.ActiveCategories.FirstOrDefault(i => i.Id == categoryId);

                    if (category != null)
                    {
                        string strCategoryId = categoryId.ToString();

                        vm.NewProduct.CategorySelectListItems.ForEach(i =>
                        {
                            i.Selected = i.Value == strCategoryId;
                        });
                    }
                }
            }
            else
            {
                var edit = result.ActiveProducts.FirstOrDefault(i => i.Id == id) ??
                           result.DeletedProducts.FirstOrDefault(i => i.Id == id);

                if (edit == null)
                {
                    return(RedirectToAction("Index"));
                }

                categoryResult.ActiveCategories.Add(edit.Category);

                vm.EditProduct = new ProductEditViewModel
                {
                    Id         = edit.Id,
                    Name       = edit.Name,
                    CategoryId = edit.CategoryId,
                    TableId    = edit.TableId,
                    CategorySelectListItems = categoryResult.ActiveCategories.Select(ToSelectListItem).ToList(),
                    TableSelectListItems    = tableResult.ActiveTables.Select(ToSelectListItem).ToList()
                };

                vm.EditProduct.CategorySelectListItems.ForEach(i =>
                {
                    i.Selected = i.Value == edit.CategoryId.ToString();
                });

                vm.EditProduct.TableSelectListItems.ForEach(i =>
                {
                    i.Selected = i.Value == edit.TableId.ToString();
                });
            }

            return(View(vm));
        }