// To Update contact record //PUT api/<controller>/id public HttpResponseMessage Put(int Id, [FromBody] TbContact _ContactToEdit) { // first fetch the details of the record to edit var ExisitngRecord = (from a in db.TbContacts where a.ContactId == Id select a ).FirstOrDefault(); //when the record is gotten if (ExisitngRecord != null) { //set the incoming records to the exitising record ExisitngRecord.ContactName = _ContactToEdit.ContactName; ExisitngRecord.Address = _ContactToEdit.Address; ExisitngRecord.DateOfBirth = _ContactToEdit.DateOfBirth; ExisitngRecord.PhoneNo = _ContactToEdit.PhoneNo; //save the changes db.SaveChanges(); //return response status as successfully updated with member entity return(Request.CreateResponse(HttpStatusCode.OK, ExisitngRecord)); } else { //return response error as NOT FOUND with message. return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Record not found to edit")); } }
public HttpResponseMessage EditContact(int id, [FromBody] TbContact NewContactValue) { try { var entity = db.TbContacts.FirstOrDefault(e => e.ContactId == id); if (entity != null) { entity.Address = NewContactValue.Address; entity.DateOfBirth = NewContactValue.DateOfBirth; entity.ContactName = NewContactValue.ContactName; entity.Email = NewContactValue.Email; entity.PhoneNo = NewContactValue.PhoneNo; //save the Updated record db.SaveChanges(); //Append/ embed the updated Data record to the request URL var Msg = Request.CreateResponse(HttpStatusCode.OK, entity); return(Msg); } else { return(Request.CreateResponse(HttpStatusCode.NotFound, "The Contact with the Id" + id.ToString() + "not found")); } } catch (Exception ex) { return(Request.CreateResponse(HttpStatusCode.BadRequest, ex)); } }
public HttpResponseMessage AddNewContact([FromBody] TbContact NewContact) { try { db.TbContacts.Add(NewContact); db.SaveChanges(); var msg = Request.CreateResponse(HttpStatusCode.Created, NewContact); //embed the ID of the new data to the Header of the request while redirecting msg.Headers.Location = new Uri(Request.RequestUri + "/" + NewContact.ContactId.ToString()); return(msg); } catch (Exception ex) { //else tell the user that there is an Issue return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex)); } }
public HttpResponseMessage Post([FromBody] TbContact _contact) { try { //to add a new record db.TbContacts.Add(_contact); // save the added data db.SaveChanges(); //return response status as successful var msg = Request.CreateResponse(HttpStatusCode.Created, _contact); //send the added data to the URi for Check Purpose msg.Headers.Location = new Uri(Request.RequestUri + _contact.ContactId.ToString()); return(msg); } catch (Exception ex) { // return response as bad request with exception message. return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex)); } }