//Metod som hanterar att lägga till en kontakt. public void ContactListView_InsertItem(Contact Contact) { if (ModelState.IsValid) { try { Service.SaveContact(Contact); Session["Status"] = true; var status = "Kontakten har lagts till!"; Response.Redirect("~/Default.aspx?status=" + status); } catch (Exception ex) { var validationResults = ex.Data["ValidationResults"] as IEnumerable<ValidationResult>; if(validationResults != null) { foreach(var validationResult in validationResults) { foreach(var memberName in validationResult.MemberNames) { ModelState.AddModelError(memberName, validationResult.ErrorMessage); } } } ModelState.AddModelError(String.Empty, "Fel inträffade när kontakt skulle läggas till."); } } }
//Sparar eller uppdaterar kontakt via DAL public void SaveContact(Contact contact) { ICollection<ValidationResult> validationResults; if(!contact.Validate(out validationResults)) { var ex = new ValidationException("Objektet klararde inte valideringen."); ex.Data.Add("ValidationResults", validationResults); throw ex; } if (contact.ContactId == 0) { ContactDAL.InsertContact(contact); } else { ContactDAL.UpdateContact(contact); } }