public async Task <ActionResult> Create([Bind(Include = "IDFilm,FilmName,Description,Time,Author,DateSubmited,Image,IDCountry,Rating,Views,LinkFilm,Trailer,Download,IDCategory,Votes")] TSql_Films tSql_Films, int[] IDCategory, HttpPostedFileBase fileimg) { if (ModelState.IsValid) { // add file img var img = Path.GetFileName(fileimg.FileName); var pathimg = Path.Combine(Server.MapPath("~/Content/images"), img); if (fileimg == null) { ViewBag.Img = "Chose images"; return(View()); } else if (System.IO.File.Exists(pathimg)) { ViewBag.Img = "Images had exists"; } else { fileimg.SaveAs(pathimg); } tSql_Films.Image = fileimg.FileName; tSql_Films.DateSubmited = DateTime.Now; db.TSql_Films.Add(tSql_Films); await db.SaveChangesAsync(); foreach (var item in IDCategory) { TSql_Film_Category tfc = new TSql_Film_Category(); tfc.IDFilm = tSql_Films.IDFilm; tfc.IDCategory = item; tfc.DateUpdate = DateTime.Now; tfc.DateCreate = DateTime.Now; db.TSql_Film_Category.Add(tfc); } db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.IDCountry = new SelectList(db.TSql_Country, "IDCountry", "CountryName", tSql_Films.IDCountry); return(View(tSql_Films)); }
public async Task <ActionResult> Edit([Bind(Include = "IDFilm,FilmName,Description,Time,Author,DateSubmited,Image,IDCountry,Rating,Views,LinkFilm,Trailer,Download, IDCategory")] TSql_Films tSql_Films, int[] IDCategory, HttpPostedFileBase fileimg) { if (ModelState.IsValid) { TSql_Films tmpFilm = db.TSql_Films.Find(tSql_Films.IDFilm); if (fileimg != null) { var img = Path.GetFileName(fileimg.FileName); var pathimg = Path.Combine(Server.MapPath("~/Content/images"), img); if (fileimg == null) { ViewBag.Img = "Chose images"; return(View()); } else if (System.IO.File.Exists(pathimg)) { ViewBag.Img = "Images had exists"; } else { fileimg.SaveAs(pathimg); } tmpFilm.Image = fileimg.FileName; } tmpFilm.FilmName = tSql_Films.FilmName; tmpFilm.Description = tSql_Films.Description; tmpFilm.Time = tSql_Films.Time; tmpFilm.Author = tSql_Films.Author; tmpFilm.LinkFilm = tSql_Films.LinkFilm; tmpFilm.Download = tSql_Films.Download; tmpFilm.Trailer = tSql_Films.Trailer; tmpFilm.IDCountry = tSql_Films.IDCountry; db.Entry(tmpFilm).State = EntityState.Modified; await db.SaveChangesAsync(); if (tmpFilm != null) { // remove item var removeitems = tmpFilm.TSql_Film_Category.Where(t => !IDCategory.Contains(t.IDCategory)).ToList(); foreach (var i in removeitems) { db.Entry(i).State = EntityState.Deleted; } // add item var additems = IDCategory.Where(t => !tmpFilm.TSql_Film_Category.Select(x => x.IDCategory).Contains(t)); foreach (var item in additems) { TSql_Film_Category tfc = new TSql_Film_Category(); tfc.IDFilm = tmpFilm.IDFilm; tfc.IDCategory = item; tfc.DateUpdate = DateTime.Now; db.TSql_Film_Category.Add(tfc); } db.SaveChanges(); return(RedirectToAction("Index")); } } ViewBag.IDCountry = new SelectList(db.TSql_Country, "IDCountry", "CountryName", tSql_Films.IDCountry); return(View(tSql_Films)); }