Пример #1
0
        public ActionResult Index()
        {
            if(User.Identity.IsAuthenticated)
            {
                ApplicationUser user = db.Users.Find(User.Identity.GetUserId());
                // создаем список книг, принадлежащих текущему пользователю
                ViewBag.UserBooks = db.Books.ToList().Find(x => x.Owner == user);
                // создаем список новых заявок, поступивших пользователю
                var suggestions = _bidHelper.CreateListOfNewBidsToUser(user);
                if (suggestions.Count > 0)
                {
                    Session["Suggestions"] = suggestions.Count;
                }
                // создаем список обработанных заявок для отображения в истории заявок
                var bids = _bidHelper.CreateBidList(user);
                int count = _bidHelper.GetNewBidsCount(bids, user);
                if (count > 0)
                    Session["Bids"] = count;
            }

            SearchBookModel model = new SearchBookModel();
            model.CreateLists();
            ViewBag.Genres = db.Genres.ToList();

            return View(model);
        }
Пример #2
0
        public ActionResult Search()
        {
            if (User.Identity.IsAuthenticated)
            {
                ApplicationUser user = db.Users.Find(User.Identity.GetUserId());
                ViewBag.UserBooks = db.Books.ToList().Find(x => x.Owner == user);
            }
            SearchBookModel model = new SearchBookModel();
            model.CreateLists();
            ViewBag.Genres = db.Genres.ToList();

            return View("Index", model);
        }
Пример #3
0
        /// <summary>
        /// Возвращает список найденных книг по запросу пользователя
        /// </summary>
        /// <param name="model"></param>
        /// <param name="selectedGenres"></param>
        /// <returns></returns>
        public List<Book> Search(SearchBookModel model, int[] selectedGenres)
        {
            List<Book> books = new List<Book>();
            // формируем строковый запрос к БД
            string query = "SELECT * FROM dbo.Books WHERE ";

            // поиск по автору
            query += model.Author != null ? "Author LIKE N'%" + model.Author + "%' and " : "";
            // поиск по названию
            query += model.Title != null ? "Title LIKE N'%" + model.Title + "%' and " : "";
            // поиск по цене
            query += (model.PriceLow != null && model.PriceHigh != null) ? "Price between " + model.PriceLow.Replace(',', '.') + " and " + model.PriceHigh.Replace(',', '.') + " and " : "";
            // поиск в интервале по году издания
            query += model.PublishYearFrom != DateTime.Now.Year ? "PublishYear between " + model.PublishYearFrom + " and " + model.PublishYearTo + " and " : "";
            // поиск по нас. пункту владельца
            query += model.Placement != null ? "Placement LIKE N'%" + model.Placement + "%' and " : "";
            int i = model.OnExchange ? 1 : 0;
            // поиск по обмену
            query += "OnExchange = " + i + " and ";
            // поиск по жанрам
            if (selectedGenres != null)
            {
                query+="Books.ID in ( SELECT Book_ID FROM dbo.GenreBooks WHERE Genre_ID IN (SELECT Genres.ID FROM dbo.Genres WHERE Genres.ID in (";
                foreach (var genre in db.Genres.Where(x => selectedGenres.Contains(x.ID)))
                {
                    query += genre.ID + ",";
                }
                query = query.Remove(query.LastIndexOf(','));
                query += "))) and ";
            }
            if (query.LastIndexOf(" and ") != -1)
            {
                query = query.Remove(query.LastIndexOf(" and "));
                books = db.Books.SqlQuery(query).ToList();
            }
            // сортируем список книг вначале по дате создания профиля по убыванию, затем - по имени владельца
            var sortedBooks = books.OrderByDescending(x => x.Created).ThenBy(x => x.Owner.Name);
            return sortedBooks.ToList();
        }
Пример #4
0
        public ActionResult Search(SearchBookModel model, int[] selectedGenres)
        {
            if(ModelState.IsValid)
            {
                double priceLow = 0;
                double priceHigh = 0;
                // проверяем диапазон цен
                if (model.PriceLow != null && model.PriceHigh != null)
                {
                    priceLow = Convert.ToDouble(model.PriceLow);
                    priceHigh = Convert.ToDouble(model.PriceHigh);
                }
                // если одно из полей диапазона заполнено, а другое нет
                if((model.PriceLow!=null && model.PriceHigh==null) ||
                        (model.PriceLow == null && model.PriceHigh != null))
                {
                    ModelState.AddModelError("", "Одно из полей не заполнено (цена)");
                }
                // проверяем диапазон годов издания
                else if (model.PublishYearFrom > model.PublishYearTo)
                {
                    ModelState.AddModelError("", "Левая граница интервала больше правой (год издания)");
                }
                else if (priceLow < 0 || priceHigh<0)
                {
                    ModelState.AddModelError("", "Некорректная цена");
                }
                else if(priceLow>priceHigh)
                {
                    ModelState.AddModelError("", "Левая граница интервала больше правой (цена)");
                }
                // если все данные корректны, выполняем поиск
                else
                {
                    List<Book> books = new List<Book>();

                    books = _searchHelper.Search(model, selectedGenres);
                    return View(books);
                }
            }

            ViewBag.Genres = db.Genres.ToList();
            model.CreateLists();

            return View("Index", model);
        }