public void Save() { renoRatorDBEntities db = new renoRatorDBEntities(); this.address.city = db.Cities.Where(c => c.cityID == this.address.cityID).FirstOrDefault(); this.address.country = "Canada"; this.address.postalCode = this.address.postalCode.Replace(" ","").Replace("-","").Trim(); List<string> tagList = new List<string>(); if (this.tags != null) { foreach (String tag in this.tags.Split(',')) tagList.Add(tag.Trim().ToLower()); this.tags = string.Join("|", tagList); } this.active = true; db.AddToJobAds(this); db.SaveChanges(); }
public ActionResult Post(FormCollection form) { if (Session["userID"] == null) return RedirectToAction("Login", "User", new { redirectPage = "Post", redirectController = "JobAd" }); _db = new renoRatorDBEntities(); var newJobAd = new JobAd(); newJobAd.address = new Address(); TryUpdateModel(newJobAd, new string[] { "address.addressLine1", "address.addressLine2", "address.postalCode", "address.cityID" }, form.ToValueProvider()); List<string> requiredFields = new List<string>(){"title","address.addressLine1","address.city.provinceID", "address.cityID","priceRangeID","description", "targetEndDate"}; // check for null fields foreach(string field in requiredFields) { if (String.IsNullOrEmpty(form[field].Trim())) ModelState.AddModelError(field, "Field is required!"); } // validate other fields if(!ValidateFunctions.validPostalCode(form["address.postalCode"])) ModelState.AddModelError("address.postalCode","Postal code is invalid!"); if(!ValidateFunctions.validDateFormat(form["targetEndDate"])) ModelState.AddModelError("targetEndDate","Date format is invalid!"); try { newJobAd.address.addressLine1 = form["address.addressLine1"]; newJobAd.address.addressLine2 = form["address.addressLine2"]; newJobAd.address.postalCode = form["address.postalCode"]; newJobAd.address.cityID = Convert.ToInt32(form["address.cityID"]); newJobAd.address.country = "Canada"; newJobAd.address.city.provinceID = Convert.ToInt32(form["address.city.provinceID"]); newJobAd.userID = (int)Session["userID"]; newJobAd.active = true; newJobAd.priceRangeID = Convert.ToInt32(form["priceRangeID"]); newJobAd.tags = form["tags"].Replace(",", "||"); newJobAd.description = form["description"]; newJobAd.targetEndDate = Convert.ToDateTime(form["targetEndDate"]); newJobAd.title = form["title"]; } catch{ } if(ModelState.IsValid) { _db.AddToJobAds(newJobAd); _db.SaveChanges(); return RedirectToAction("Index"); } // Otherwise, reshow form TryUpdateModel(newJobAd); populateDropdowns(); return View(newJobAd); }