Consume Web API Post method in ASP.NET MVC
In the previous section, we learned how to consume Web API Get method and display records in the ASP.NET View. Here, we will see how to consume Post method of Web API to create a new record in the data source.
We already created Web API with Post method in the Implement Post Method section shown below.
public class StudentController : ApiController
{
public StudentController()
{
}
//Get action methods of the previous section
public IHttpActionResult PostNewStudent(StudentViewModel student)
{
if (!ModelState.IsValid)
return BadRequest("Not a valid model");
using (var ctx = new SchoolDBEntities())
{
ctx.Students.Add(new Student()
{
StudentID = student.Id,
FirstName = student.FirstName,
LastName = student.LastName
});
ctx.SaveChanges();
}
return Ok();
}
}
In the above Web API, PostNewStudent
method will handle HTTP POST request http://localhost:64189/api/student
. It will insert new record in the database using Entity Framework and will return 200 OK response status.
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; }
}
Now, let's create MVC view to create a new record by consuming the above Web API Post method.
Step 1:
First, we need to add action method "create" which will render "Create New Student" view where user can enter data and submit it. We have already created StudentController class in the previous section to display student list view. Here, add "create" action method to render "Create New Student" view shown below.
public class StudentController : Controller
{
public ActionResult Index()
{
//consume Web API Get method here..
return View();
}
public ActionResult create()
{
return View();
}
}
Now, right click in the above action method and select Add View.. This will open following Add View popup.
Now, select Create Template, StudentViewModel class as a model and click on Add button as shown above. This will generate createcshtml in the Views > Student folder as below.