kez kez - 10 months ago 51
C# Question

Edit method in web api

I have following class , its using Entity Frameworks to operate its tasks

Repository Class

public class LibraryRepository
LibraryContext context = new LibraryContext();

public void EditBook(Book book)
context.Entry(book).State = System.Data.Entity.EntityState.Modified;

so I'm trying to use this EditBook method in my Web API

Web API Controller Class

public class BooksWebAPIController : ApiController
private LibraryRepository db = new LibraryRepository();

public IHttpActionResult PutBook(int id, Book book)
if (!ModelState.IsValid)
return BadRequest(ModelState);

if (id != book.Book_Id)
return BadRequest();


return StatusCode(HttpStatusCode.NoContent);

I'm trying use above Web API
URL in MVC project(as my client layer)
So I have created a client class in MVC project's
folder like below

LibraryClient Class

public class LibraryClient
private string BOOK_URL = "http://localhost:13793/api/Books";

public bool Edit(Book book)
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(BOOK_URL);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.PutAsJsonAsync("Books/" + book.Book_Id, book).Result;

return response.IsSuccessStatusCode;
return false;


Then in MVC Project's Controller Folder I have created following class and controllers to interact with front end

BooksController Class

public class BooksController : Controller
public ActionResult Edit(int id)
LibraryClient lc = new LibraryClient();
Book book = new Book();
book = lc.GetBook(id);

return View("Edit", book);

public ActionResult Edit(Book book)
LibraryClient pc = new LibraryClient();
return RedirectToAction("BookswithAuthers", "BookWithAuther");

But here this is compiling without any errors, when I select a book to edit its fetching correct book , but once I'm doing change of it and hit save its not saving updated details , whats wrong in my approach.

The methods
created like this approach working fine. only issue is this

Answer Source

Are you calling context.SaveChanges() anywhere? If not, call it after context.Entry(book).State = System.Data.Entity.EntityState.Modified; .