In this session, I will show you how to insert records using AA Web API using HttpClient to post data in SQL Server. In this session, you can see get and post operations by Web API. In another way, I can say we'll insert and retrieve records using button click event.
Before going through this session, visit my previous session.
During page initial load table data will be shown that means the data will bind in table with input controls uisng HttpClient. This controller action method with [HttpGet].
Step 2
Using same Action to the HomeController (in MVC Client application) for Post data using HTTP Client.
Code Ref
- [HttpPost]
- public ActionResult Part4(Employee emp)
- {
- if (ModelState.IsValid)
- {
- HttpClient client = new HttpClient();
- var result = client.PostAsJsonAsync("http://localhost:47250/api/satya", emp).Result;
- if (result.IsSuccessStatusCode)
- {
- emp = result.Content.ReadAsAsync<Employee>().Result;
- ViewBag.Result = "Data Is Successfully Saved!";
- List<Employee> list = new List<Employee>();
- HttpClient client1 = new HttpClient();
- var result1 = client1.GetAsync("http://localhost:47250/api/satya").Result;
- if (result1.IsSuccessStatusCode)
- {
- list = result1.Content.ReadAsAsync<List<Employee>>().Result;
- ViewBag.userdetails = list;
- }
- ModelState.Clear();
- return View(new Employee());
- }
- else
- {
- ViewBag.Result = "Error! Please try with valid data.";
- }
- }
- return View(emp);
- }
Code Description
In this part after form post method or button click event, data insert and tables data wil be shown. In side post section I added soemthing for data retrieval otherwise you'll get an error about Object reference not being set to an instance of an object. I will describe this issue in view section under Note.
- List<Employee> list = new List<Employee>();
- HttpClient client1 = new HttpClient();
- var result1 = client1.GetAsync("http://localhost:47250/api/satya").Result;
- if (result1.IsSuccessStatusCode)
- {
- list = result1.Content.ReadAsAsync<List<Employee>>().Result;
- ViewBag.userdetails = list;
- }
Model state dictionary object that contains state of the model and of model binding validation, removes all items from model state dictionary.
Right Click on Action Method (here right click on form Part4()) > Add View... > Check "Create strongly typed view" > Select Model class >> Add. Here Model Class is "Employee (Entities)".
Code Ref
- @model Entities.Employee
-
- @{
- ViewBag.Title = "Satyaprakash - Post data to Web API using HTTPClient (in MVC client application) With Validation";
- }
-
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
- <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
-
-
- <script src="https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/4.4.0/bootbox.min.js">
-
- </script>
-
- <style>
- span.field-validation-error {
- color: red;
- }
-
- table {
- font-family: arial, sans-serif;
- border-collapse: collapse;
- width: 100%;
- }
-
- td, th {
- border: 1px solid #dddddd;
- text-align: left;
- padding: 8px;
- }
-
- tr:nth-child(even) {
- background-color: #dddddd;
- }
-
- .button {
- background-color: #4CAF50;
- border: none;
- color: white;
- padding: 15px 32px;
- text-align: center;
- text-decoration: none;
- display: inline-block;
- font-size: 16px;
- margin: 4px 2px;
- cursor: pointer;
- }
-
- .button4 {
- border-radius: 9px;
- }
- </style>
-
-
- <div style="padding:10px ; align-content:center">
- <fieldset>
- <legend style="font-family:Arial Black;color:blue">Post data to Web API using HTTPClient (in MVC client application) With Validation</legend>
- </fieldset>
- </div>
-
-
- <div style="max-width:600px;">
- @using (Html.BeginForm("Part4", "Home", FormMethod.Post, new { role = "form" }))
- {
- @Html.ValidationSummary(true)
-
- <div class="form-group">
- @Html.LabelFor(a => a.FirstName)
- @Html.TextBoxFor(a => a.FirstName, new { @class = "form-control" })
- @Html.ValidationMessageFor(a => a.FirstName)
- </div>
- <div class="form-group">
- @Html.LabelFor(a => a.LastName)
- @Html.TextBoxFor(a => a.LastName, new { @class = "form-control" })
- @Html.ValidationMessageFor(a => a.LastName)
- </div>
- <div class="form-group">
- @Html.LabelFor(a => a.EmailID)
- @Html.TextBoxFor(a => a.EmailID, new { @class = "form-control" })
- @Html.ValidationMessageFor(a => a.EmailID)
- </div>
- <div class="form-group">
- @Html.LabelFor(a => a.City)
- @Html.TextBoxFor(a => a.City, new { @class = "form-control" })
- @Html.ValidationMessageFor(a => a.City)
- </div>
- <div class="form-group">
- @Html.LabelFor(a => a.Country)
- @Html.TextBoxFor(a => a.Country, new { @class = "form-control" })
- @Html.ValidationMessageFor(a => a.Country)
- </div>
- <input id="btn" type="submit" value="Create" class="button button4" />
-
- <div style="width:90%; padding:10px; margin:0 auto;">
- @if (ViewBag.Result != null)
- {
- @*<div style="color:red">@ViewBag.Result</div>*@
-
- <script>
- $(document).ready(function () {
- $('#btn').click(function () {
- $('#tableshow').hide();
- });
-
- bootbox.alert('@ViewBag.Result');
- $('#tableshow').show();
- });
- </script>
- }
- </div>
- }
- </div>
-
- @*System.NullReferenceException , Object reference not set to an instance of an object. This error due to without added for data retrieve comment line code in Part4() in homecontroller in webapplication*@
- <div id="tableshow" style="width:90%; padding:10px; margin:0 auto;">
- <table class="table table-responsive table-striped table-bordered">
- <thead>
- <tr>
- <th style="background-color: Yellow;color: blue">Full Name</th>
- <th style="background-color: Yellow;color: blue">Email</th>
- <th style="background-color: Yellow;color: blue">City</th>
- <th style="background-color: Yellow;color: blue">Country</th>
- </tr>
- </thead>
- <tbody>
- @foreach (var i in ViewBag.userdetails)
- {
- <tr>
- <td>@i.FirstName @i.LastName</td>
- <td>@i.EmailID</td>
- <td>@i.City</td>
- <td>@i.Country</td>
- </tr>
- }
- </tbody>
- </table>
- </div>
- @*System.NullReferenceException , Object reference not set to an instance of an object.*@
-
- @section Scripts{
- @Scripts.Render("~/bundles/jqueryval")
- }
Code Description
In this code section inside form post method added a script so that during button click event table data will be shown.
- <div style="width:90%; padding:10px; margin:0 auto;">
- @if (ViewBag.Result != null)
- {
- @*<div style="color:red">@ViewBag.Result</div>*@
-
- <script>
- $(document).ready(function () {
- $('#btn').click(function () {
- $('#tableshow').hide();
- });
-
- bootbox.alert('@ViewBag.Result');
- $('#tableshow').show();
- });
- </script>
- }
- </div>
Here I used bootbox library to show alert notification. ViewBag.Result contains message in controller action method.
- bootbox.alert('@ViewBag.Result');
Note
During this session I was facing an issue about System.NullReferenceException, Object reference is not set to an instance of an object.
So, iIcreated a div id and put it inside script section as described in post method of Part4() controller action method. This error was due to lack of added data for data retrieval comment line code in Part4() in homecontroller in MVC client application.
- <div id="tableshow" style="width:90%; padding:10px; margin:0 auto;">
- <table class="table table-responsive table-striped table-bordered">
- <thead>
- <tr>
- <th style="background-color: Yellow;color: blue">Full Name</th>
- <th style="background-color: Yellow;color: blue">Email</th>
- <th style="background-color: Yellow;color: blue">City</th>
- <th style="background-color: Yellow;color: blue">Country</th>
- </tr>
- </thead>
- <tbody>
- @foreach (var i in ViewBag.userdetails)
- {
- <tr>
- <td>@i.FirstName @i.LastName</td>
- <td>@i.EmailID</td>
- <td>@i.City</td>
- <td>@i.Country</td>
- </tr>
- }
- </tbody>
- </table>
- </div>
OUTPUT
During page load event.
Mobile view support.
Gif image for better understanding about output.
Check sql server for inserting records as shown in the above image.
Link To Source Code
SUMMARY
- Get and Post data with form control validation using HTTP Client.
- Bootbox javascript library for alert message.
- Mobile responsive support.