public ActionResult NewsAdd(News model) { if (ModelState.IsValid) { string uniqueFileName = null; // If the Photo property on the incoming model object is not null, then the user // has selected an image to upload. if (model.News_image != null) { // The image must be uploaded to the images folder in wwwroot // To get the path of the wwwroot folder we are using the inject // HostingEnvironment service provided by ASP.NET Core string uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "uploadimages"); // To make sure the file name is unique we are appending a new // GUID value and and an underscore to the file name uniqueFileName = Guid.NewGuid().ToString() + "_" + model.News_image.FileName; string filePath = Path.Combine(uploadsFolder, uniqueFileName); // Use CopyTo() method provided by IFormFile interface to // copy the file to wwwroot/images folder model.News_image.CopyTo(new FileStream(filePath, FileMode.Create)); } Tbnews news = new Tbnews { NewsContent = model.NewsContent, NewscateId = model.NewscateId, Datecreated = model.Datecreated, NewsSummary = model.NewsSummary, NewsTitle = model.NewsTitle, // Store the file name in PhotoPath property of the employee object // which gets saved to the Employees database table NewsImage = "/uploadimages/" + uniqueFileName }; db.SaveNews(news); return(RedirectToAction("TinTuc")); } return(View()); }
public void SaveNews(Tbnews model) { if (model.NewsId == 0) { context.Tbnews.Add(model); } else { Tbnews news = context.Tbnews .FirstOrDefault(p => p.NewsId == model.NewsId); if (news != null) { news.NewsContent = model.NewsContent; news.NewscateId = model.NewscateId; news.Datecreated = model.Datecreated; news.NewsSummary = model.NewsSummary; news.NewsTitle = model.NewsTitle; news.NewsImage = model.NewsImage; news.Datemodified = DateTime.Now; } } context.SaveChanges(); }