public ActionResult EditPost(Contact contact) { ViewBag.StatusList = status; if (ModelState.IsValid) { HttpResponseMessage response = null; try { ViewBag.StatusList = status; ContactsAPI.Models.DBModel.Contact c = TranslateForPost(contact); Task <HttpResponseMessage> putTask = client.PutAsJsonAsync <ContactsAPI.Models.DBModel.Contact>("ContactsAPI", c); putTask.Wait(); response = putTask.Result; if (response.IsSuccessStatusCode) { TempData["Status"] = "Successfully edited"; return(RedirectToAction("Index")); } if (response != null) { if (response.StatusCode == System.Net.HttpStatusCode.NotFound) { ModelState.AddModelError(string.Empty, "item Not Found"); } else if (response.StatusCode == System.Net.HttpStatusCode.Conflict) { ModelState.AddModelError(string.Empty, response.Content.ReadAsStringAsync().Result); } else { ModelState.AddModelError(string.Empty, "Some internal error occurred"); } } return(View(contact)); } catch (Exception) { if (response != null) { ModelState.AddModelError(string.Empty, "Some internal error occurred. Please try again."); } return(View(contact)); } } else { return(View(contact)); } }
private ContactsAPI.Models.DBModel.Contact TranslateForPost(Contact source) { ContactsAPI.Models.DBModel.Contact target = new ContactsAPI.Models.DBModel.Contact(); foreach (var src in source.GetType().GetProperties()) { foreach (var trgt in target.GetType().GetProperties()) { if (src.Name.ToUpper() == trgt.Name.ToUpper()) { trgt.SetValue(target, src.GetValue(source)); } } } return(target); }
public ActionResult Create(Contact contact) { ViewBag.StatusList = status; if (ModelState.IsValid) { HttpResponseMessage response = null; try { ViewBag.StatusList = status; ContactsAPI.Models.DBModel.Contact c = TranslateForPost(contact); Task <HttpResponseMessage> postTask = client.PostAsJsonAsync <ContactsAPI.Models.DBModel.Contact>("ContactsAPI", c); postTask.Wait(); response = postTask.Result; if (response.IsSuccessStatusCode) { TempData["Status"] = "Successfully added"; return(RedirectToAction("Index")); } if (response != null) { ModelState.AddModelError(string.Empty, response.Content.ReadAsStringAsync().Result); } return(View(contact)); } catch (Exception e) { if (response != null) { ModelState.AddModelError(string.Empty, "Some internal error occurred"); } return(View(contact)); } } else { return(View(contact)); } }