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.
Example: Sample Web API with Post Method
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.
Example: Model Class
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.
Example: MVC Controller
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.
create.cshtml
@model WebApiDemo.Models.StudentViewModel
@{
ViewBag.Title = "Create New Student - MVC";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Create New Student</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
In the above view,
Html.BeginForm()
generates HTML form tag <form> action="/Student/Create" method="post" </form>
which will send post request when user clicks on the create button.
Now, run the project and navigate to
http://localhost:64189/student/create
. It will display the simple data entry view as shown below.
Now, on the click of create button above, it will insert a new record in the DB and redirect to the list view as shown below.
Also, the above create view will display an error message if Web API sends error response as shown below.
So in this way we can consume Post method of Web API to execute HTTP POST request to create a new record.
Next, consume Put method of Web API to edit an existing record.
No comments:
Post a Comment