Example #1
0
        public async Task <IActionResult> Add([FromForm] WidgetViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            try
            {
                var lastWidget = _dbContext.Widgets.OrderBy(f => f.Id).LastOrDefault();
                var widget     = new Widget()
                {
                    //LongUrl = model.LongUrl,
                    Name        = model.Name,
                    CreatedDate = DateTime.UtcNow,
                    Yandex      = model.Yandex,
                    Google      = model.Google,
                    TwoGIS      = model.TwoGIS
                };

                if (lastWidget != null)
                {
                    widget.Id = lastWidget.Id + 1;
                }



                _dbContext.Widgets.Add(widget);
                await _dbContext.SaveChangesAsync();

                widget.Link = _urlGenerator.Encode(widget.Id);
                _dbContext.Update(widget);
                await _dbContext.SaveChangesAsync();

                return(RedirectToAction(nameof(HomeController.Index), this.UrlName <HomeController>()));
            }
            catch
            {
                ModelState.AddModelError(string.Empty, "На сервере произошла ошибка, попробуйте позже");
                return(View(model));
            }
        }