Exemplo n.º 1
0
        public async Task <IActionResult> SaveForm(PostFormViewModel postVM, IFormFile pic)
        {
            //if not valid, return the user the New Post page
            if (!ModelState.IsValid)
            {
                var vM = new PostFormViewModel()
                {
                    Campuses = _campus.GetAll(),
                    Statuses = _posts.GetListOfStatus()
                };

                return(View("PostForm", vM));
            }

            var userId = userManager.GetUserId(User);
            var user   = await userManager.FindByIdAsync(userId);

            var post = new Post
            {
                Id          = postVM.Id,
                Title       = postVM.Title,
                Description = postVM.Description,
                DateCreated = postVM.DateCreated,
                Url         = postVM.Url,
                Status      = postVM.Status,
                PostType    = postVM.PostType,
                Campus      = _campus.GetById(postVM.Campus.Id),
                User        = user
            };

            //if true, then it's a new post
            if (postVM.Id == 0)
            {
                string filename = string.Empty;

                //upload image if not null
                if (pic != null)
                {
                    filename = UploadImage(pic);
                    post.Url = "/images/" + Path.GetFileName(pic.FileName);
                }

                if (_posts.AddNewPost(post))
                {
                    return((postVM.PostType == PostType.Issue) ? RedirectToAction("Issues") : RedirectToAction("Events"));
                }
            }
            else
            {
                if (_posts.EditPost(post))
                {
                    return(RedirectToAction("Detail", new { postVM.Id }));
                }
            }

            return(BadRequest());
        }