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();
[ResponseType(typeof(void))]
public IHttpActionResult PutBook(int id, Book book)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != book.Book_Id)
{
return BadRequest();
}
db.EditBook(book);
return StatusCode(HttpStatusCode.NoContent);
}
}
I'm trying use above Web API EditBook URL in MVC project(as my client layer)
So I have created a client class in MVC project's Model folder like below
LibraryClient Class
public class LibraryClient
{
private string BOOK_URL = "http://localhost:13793/api/Books";
public bool Edit(Book book)
{
try
{
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;
}
catch
{
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
{
[HttpGet]
public ActionResult Edit(int id)
{
LibraryClient lc = new LibraryClient();
Book book = new Book();
book = lc.GetBook(id);
return View("Edit", book);
}
[HttpPost]
public ActionResult Edit(Book book)
{
LibraryClient pc = new LibraryClient();
pc.Edit(book);
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 View,Create and Delete created like this approach working fine. only issue is this Edit method
Are you calling context.SaveChanges() anywhere? If not, call it after context.Entry(book).State = System.Data.Entity.EntityState.Modified; .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With