public ActionResult UpdateWard(WardViewModel ward) { //format data Ward data = new Ward() { ID = ward.Id, Name = ward.WardName, DistrictID = ward.DistrictId }; //validate data if (_wardService.Validate(data) == false) { return(Json(new { Status = "error", Data = "Địa chỉ không đúng" }, JsonRequestBehavior.AllowGet)); } try { //check address name is exist if (_wardService.ContainWith(data)) { return(Json(new { Status = "error", Data = "Địa chỉ đã tồn tại" }, JsonRequestBehavior.AllowGet)); } //insert or update var w = _wardService.SelectById(ward.Id); if (w == null) //ward is not found { //add new ward _wardService.Insert(new Ward() { Name = ward.WardName, DistrictID = ward.DistrictId, IsDelete = false }); //get id of new ward var wardAfterInsert = _wardService.GetAll() .SingleOrDefault(wa => wa.Name == ward.WardName && wa.DistrictID == ward.DistrictId); ward.Id = wardAfterInsert?.ID ?? -1; } else { //update ward w.Name = ward.WardName; w.DistrictID = ward.DistrictId; _wardService.Update(w); } //format result return var resultResult = new { data = ward, flag = 0 }; return(Json(new { Status = "success", Data = resultResult }, JsonRequestBehavior.AllowGet)); } catch (Exception ex) { return(Json(new { Status = "error", Data = "Server bị lỗi" })); } }