예제 #1
0
        public async Task<ActionResult> AddNote(NoteAddModel noteModel, HttpPostedFileBase imagePath, HttpPostedFileBase[] file)
        {
            if (noteModel.CategoryId == 0)
            {
                ModelState.AddModelError("CategoryId", "Выберите категорию.");
                ViewBag.Categories = await UserNoteService.GetCategoriesForUserAsync(User.Identity.Name);
                return View();
            }
            if (ModelState.IsValid)
            {
                //если изображение загружено
                if (imagePath != null)
                {
                    //сохраняем изображение в папку сайта
                    string imageName = Path.GetFileName(imagePath.FileName);
                    int startIndex = imageName.LastIndexOf('.');
                    imageName = imageName.Insert(startIndex
                        , DateTime.Now.ToString("dd/MM/yyyy H:mm:ss").Replace(':', '_').Replace('/', '.').Replace(' ', '_'));
                    imagePath.SaveAs(Server.MapPath("~/Images/Note/" + imageName));
                    noteModel.ImagePath = "~/Images/Note/" + imageName;
                }
                //если загружены доп файлы
                if (file != null && file[0] != null)
                {
                    noteModel.Files = new List<FileForNoteAddModel>();
                    foreach (var item in file)
                    {
                        string fileName = Path.GetFileName(item.FileName);
                        item.SaveAs(Server.MapPath("~/Files/TempFiles/" + fileName));
                        noteModel.Files.Add(new FileForNoteAddModel { Path = "~/Files/TempFiles/" + fileName, Size = item.ContentLength, Name = fileName });
                    }
                }
                noteModel.UserId = await UserNoteService.GetUserIdByNameAsync(User.Identity.Name);
                var result = await UserNoteService.AddNewNoteAsync(noteModel);
                if (result != null)
                {
                    ViewBag.Title = "Запись добавлена";
                    ViewBag.Result = "Запись успешно добавлена и ожидает проверки администратором.";
                    return View("Success");
                }
                else
                {
                    return HttpNotFound();
                }

            }
            return View();
        }
예제 #2
0
        //добавление новой записи пользователем
        public async Task<NoteAddModel> AddNewNoteAsync(NoteAddModel noteModel)
        {
            if (noteModel == null)
            {
                return null;
            }
            //создаём запись
            Note noteAdd = new Note
            {
                Title = noteModel.Title,
                Description = noteModel.Description,
                ImagePath = noteModel.ImagePath,
                Status = "Ожидает модерацию",
                CatalogUserId = noteModel.UserId,
                CategoryId = noteModel.CategoryId,
                Date = DateTime.Now,
            };
            
            if (noteModel.Files != null)
            {
                //добавляем прикрепляемы файлы
                foreach (var file in noteModel.Files)
                {
                    File fileAdd = new File
                    {
                        FileName = file.Name,
                        Path = file.Path,
                        Size = file.Size
                    };
                    noteAdd.Files.Add(fileAdd);
                }
            }

            if (!String.IsNullOrEmpty(noteModel.Tags))
            {
                var tags = await JsonConvert.DeserializeObjectAsync<TagForNoteAddModel[]>(noteModel.Tags);
                //добовляем тэги
                foreach (var tag in tags)
                {
                    //если тэг отсутствовал в БД, добовляем его
                    if (tag.Id == 0)
                    {
                        noteAdd.Tags.Add(new Tag { Id = tag.Id, Name = tag.Name });
                    }
                    //если тэг присутствовал, берём существующий
                    else
                    {
                        noteAdd.Tags.Add(await Database.Tags.GetAsync(tag.Id));
                    }                    
                }
            }

            if (!String.IsNullOrEmpty(noteModel.NoteSpecifications))
            {
                var specif = await JsonConvert.DeserializeObjectAsync<SpecificationsForNoteAddModel[]>(noteModel.NoteSpecifications);
                //добовляем характеристики
                foreach (var sp in specif)
                {
                    //если характеристика отсутствовала в БД, добовляем её
                    if (sp.SpecificationId == 0)
                    {
                        noteAdd.NoteSpecifications.Add(new NoteSpecification
                        {
                            Specification = new Specification
                            {
                                Id = sp.SpecificationId,
                                Title = sp.Title,
                                CategoryId = noteModel.CategoryId
                            },
                            SpecificationId = sp.SpecificationId,
                            Value = sp.Value,
                        });
                    }
                    else
                    {
                        noteAdd.NoteSpecifications.Add(new NoteSpecification
                        {
                            SpecificationId = sp.SpecificationId,
                            Value = sp.Value,
                        });
                    }
                }
            }         
            //добовляем запись в БД
            Database.Notes.Create(noteAdd);
            //сохраняем результат
            int result = await Database.SaveAsync();

            return result > 0 ? noteModel : null;
        }