We have already created Web API with Delete method that handles HTTP DELETE request in the Implement Delete Method section as below.
public class StudentController : ApiController
{
public StudentController()
{
}
public IHttpActionResult Delete(int id)
{
if (id <= 0)
return BadRequest("Not a valid student id");
using (var ctx = new SchoolDBEntities())
{
var student = ctx.Students
.Where(s => s.StudentID == id)
.FirstOrDefault();
ctx.Entry(student).State = System.Data.Entity.EntityState.Deleted;
ctx.SaveChanges();
}
return Ok();
}
}
The following is a Student list view created in the Consuming get method in MVC section. Here, we will implement delete functionality when user clicks on the Delete link in the following UI.
When user clicks on the Delete link in the above UI, it sends HTTP Get request http://localhost:64189/student/delete/{id}
to the Student controller with the current id parameter. So let's implement delete functionality by consuming Web API Delete method.
Step 1:
Create HttpGet action method Delete with id parameter in the MVC StudentController
as shown below.
public class StudentController : Controller
{
// GET: Student
public ActionResult Index()
{
IList<StudentViewModel> students = null;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:64189/api/student");
//HTTP GET
var responseTask = client.GetAsync("student");
responseTask.Wait();
var result = responseTask.Result;
if (result.IsSuccessStatusCode)
{
var readTask = result.Content.ReadAsAsync<IList<StudentViewModel>>();
readTask.Wait();
students = readTask.Result;
}
}
return View(students);
}
public ActionResult Delete(int id)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:64189/api/");
//HTTP DELETE
var deleteTask = client.DeleteAsync("student/" + id.ToString());
deleteTask.Wait();
var result = deleteTask.Result;
if (result.IsSuccessStatusCode)
{
return RedirectToAction("Index");
}
}
return RedirectToAction("Index");
}
}
As you can see, Delete() action method above uses HttpClient
to send HTTP DELETE request with the current id parameter. The Web API controller shown in the first code example, will handle this DELETE request and delete the record from the data source. Visit HttpClient section to learn more about it.
So, in this way you can consume Delete method of Web API in ASP.NET MVC.
No comments:
Post a Comment