public ActionResult Create() { var db = new ApplicationDbContext(); Advertisement ad = new Advertisement(); ad.CategoryList = db.Category.ToList(); return View(ad); }
public ActionResult Create(Advertisement advertisement, HttpPostedFileBase[] fileUpload2, HttpPostedFileBase[] fileUpload, string[] description, int? cat) { try { if (ModelState.IsValid) { using (var db = new ApplicationDbContext()) { if(!checkBannedWords(advertisement.Title)||!checkBannedWords(advertisement.Content)) { return RedirectToAction("Index"); // TU DODAAC CO MA SIE STAC } foreach(var desc in description) { if(!checkBannedWords(desc)) { return RedirectToAction("Index"); // TU DODAAC CO MA SIE STAC } } string login = User.Identity.GetUserName(); var user = db.Users.FirstOrDefault(u => u.UserName==login); advertisement.User = user; advertisement.UserId = user.Id; advertisement.CategoryId = 1; advertisement.Category = db.Category.FirstOrDefault(u => u.CategoryId == 1); advertisement.AddedDate = DateTime.Now; db.Advertisement.Add(advertisement); db.SaveChanges(); int lastItemId = db.Advertisement.Max(item => item.AdvertisementId); if (!Directory.Exists(Server.MapPath("~/advertisements"))) { Directory.CreateDirectory(Server.MapPath("~/advertisements")); } Directory.CreateDirectory(Server.MapPath("~/advertisements/" + lastItemId)); foreach (var file in fileUpload2) { String pathToDb = "~/advertisements/" + lastItemId + "/" + file.FileName; String path = Server.MapPath(pathToDb); file.SaveAs(path); Models.File newFile = new Models.File(); newFile.AdvertisementId = lastItemId; newFile.Advertisement = advertisement; newFile.Path = pathToDb; newFile.InDetails = true; db.File.Add(newFile); db.SaveChanges(); } foreach (var file in fileUpload) { int i = 0; String pathToDb = "~/advertisements/" + lastItemId + "/" + file.FileName; String path = Server.MapPath(pathToDb); file.SaveAs(path); Models.File newFile = new Models.File(); newFile.AdvertisementId = lastItemId; newFile.Advertisement = advertisement; newFile.Path = pathToDb; newFile.InDetails = false; if (description[i] != "") newFile.Description = description[i]; else newFile.Description = null; db.File.Add(newFile); db.SaveChanges(); i++; } } return RedirectToAction("Index"); } return RedirectToAction("Index"); } catch { return View(); } }