Consume Web API Put method in ASP.NET MVC
In the previous two sections, we learned how to consume Web API Get and Post methods in the ASP.NET View. Here, we will see how to consume Put method of Web API to update an existing record.
We already created Web API with Put method that handles HTTP PUT request in the Implement Put Method section as below.
public class StudentController : ApiController
{
public StudentController()
{
}
public IHttpActionResult Put(StudentViewModel student)
{
if (!ModelState.IsValid)
return BadRequest("Not a valid data");
using (var ctx = new SchoolDBEntities())
{
var existingStudent = ctx.Students.Where(s => s.StudentID == student.Id).FirstOrDefault<Student>();
if (existingStudent != null)
{
existingStudent.FirstName = student.FirstName;
existingStudent.LastName = student.LastName;
ctx.SaveChanges();
}
else
{
return NotFound();
}
}
return Ok();
}
}
We created Student List view in the previous section as below. In the below view there is an edit link for each record to edit that particular record. We will handle edit functionality in this section.
The following is a Web API + MVC project structure created in the previous sections. We will add necessary classes in this project.
We have already created the following StudentViewModel class under Models folder.
public class StudentViewModel
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public AddressViewModel Address { get; set; }
public StandardViewModel Standard { get; set; }
}