示例#1
0
        public ActionResult Create(PostViewModel postViewModel)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var folderName = "upload/";
                    foreach (IFormFile file in postViewModel.Photos)
                    {
                        var savePath = Path.Combine(_enviroment.WebRootPath, folderName,
                                                    file.FileName);

                        using (var photoFile = new FileStream(savePath, FileMode.Create))
                        {
                            file.CopyTo(photoFile);
                        }
                    }
                    //folderName+"/"+postViewModel.Photos.FileName
                    var            newTags  = postViewModel.CommaSeparatedTags.Split(",");
                    List <PostTag> listTags = new List <PostTag>();
                    foreach (var s in newTags)
                    {
                        if (_context.Tags.Where(x => x.Name == s).Any())
                        {
                            listTags.Add(new PostTag {
                                Tag = _context.Tags.Where(x => x.Name == s).First()
                            });
                        }
                        else
                        {
                            listTags.Add(new PostTag {
                                Tag = new Tag {
                                    Name = s
                                }
                            });
                        }
                    }
                    // Select(x =>new PostTag{x.Tag = _context.Tags.Where} )
                    _context.AddPost(new Post
                    {
                        Id         = Guid.NewGuid(),
                        Title      = postViewModel.Title,
                        PhotosPath = postViewModel.Photos.Select(p => folderName + "/" + p.FileName),
                        PostTags   = listTags
                                     //postViewModel.CommaSeparatedTags
                                     //.Split(",")
                                     //.Select(x => new PostTag { Tag =new Tag { Name = x } })
                                     //.ToList()

                                     //PostTags.Tags = postViewModel.CommaSeparatedTags
                                     //.Split(",")
                                     //.Select(x => new Tag { Name =x})
                                     //.ToList()
                    });
                    return(RedirectToAction(nameof(Index)));
                }
                return(View(postViewModel));
            }
            catch
            {
                return(View());
            }
        }