Introduction
In this post, I am going to explain How to post data with validation in the ASP.NET Web API using JqueryIn the previous part I have explained Part1 - How to retrieve data from the database in the ASP.NET Web API using Jquery and Part 2 - How to retrieve data from the database in the ASP.NET Web API using Http Client
- Part1 - How to retrieve data from the database in the ASP.NET Web API using Jquery
- Part 2 - How to retrieve data from the database in the ASP.NET Web API using Http Client
- Part 3 - How to post data with validation in the ASP.NET Web API using Jquery
- Part 4 - How to post data with validation in the ASP.NET Web API using Http Client
- Part 5 - How to upload files in the ASP.NET Web API using Jquery
- Part 6 - How to upload files in the ASP.NET Web API using Http Client
- Part 7 - How to retrieve and display data With Paging in the ASP.NET Web API using Jquery
Steps for "Entities" project
Step - 1 : Apply validation on Model.
Go to Solution Explorer > Entities (Project name) > MyModel.tt > Open Employee.csnamespace Entities { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; public partial class Employee { public int EmployeeID { get; set; } [Required(ErrorMessage="First name required", AllowEmptyStrings=false)] public string FirstName { get; set; } [Required(ErrorMessage="Last name required", AllowEmptyStrings=false)] public string LastName { get; set; } [RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$", ErrorMessage="E-mail is not valid")] public string EmailID { get; set; } public string City { get; set; } public string Country { get; set; } } }
Steps for Web API Application(Service)
Here in this example, the Web API application (service) is "WebApiExample".Step-2 : Add a new Action to the HomeController (in MVC Client application) for get view for post data
public HttpResponseMessage Post(Employee emp) { HttpResponseMessage response; if (ModelState.IsValid) { using (MyDatabaseEntities dc= new MyDatabaseEntities()) { dc.Employees.Add(emp); dc.SaveChanges(); } response = Request.CreateResponse(HttpStatusCode.Created, emp); } else { response = Request.CreateResponse(HttpStatusCode.BadRequest, "Error! Please try again with valid data."); } return response; }
Steps for Web Application (Client Application)
Here in this example, the client application is "WebApiClient.Web".Step-3: Add a new Action to the HomeController (in MVC Client application) for get view for Post data
public ActionResult Part3() { return View(); }
Step-4: Add view for the Action & design.
Right Click on Action Method (here right click on form action) > Add View... > Enter Name > Add.View
@{ ViewBag.Title = "Part3"; } <style> .error, #error { color:red; display:none; } </style> <h2>Part3 - Post data to Web API using Jquery.</h2> <div class="container1"> <form id="frm1" role="form" style="max-width:500px"> <div class="form-group"> <div id="error"> </div> </div> <div class="form-group"> <label for="firstname">First Name:</label> <input type="text" class="form-control" id="firstname"> <span class="error">Please provide First Name</span> </div> <div class="form-group"> <label for="lastname">Last Name:</label> <input type="text" class="form-control" id="lastname"> <span class="error">Please provide Last Name</span> </div> <div class="form-group"> <label for="email">Email:</label> <input type="text" class="form-control" id="email"> <span class="error">Invalid email ID</span> </div> <div class="form-group"> <label for="city">City:</label> <input type="text" class="form-control" id="city"> </div> <div class="form-group"> <label for="country">Country:</label> <input type="text" class="form-control" id="country"> </div> <button type="submit" class="btn btn-default">Submit</button> </form> </div>
Step-5: Add jquery code into the view for post data to web api for save to the database.
Jquery Code<script> $(document).ready(function () { var apiBaseUrl = "http://localhost:1963/"; $('#frm1').submit(function (e) { e.preventDefault(); var isOK = ValidateForm(); if (isOK) { var emp = { EmployeeID: 0, FirstName: $('#firstname').val().trim(), LastName: $('#lastname').val().trim(), EmailID: $('#email').val().trim(), City: $('#city').val().trim(), Country: $('#country').val().trim() }; //Save $.ajax({ url: apiBaseUrl+'api/example', type: 'POST', dataType: 'json', data: emp, success: function (d) { alert('Successfully Saved!'); var frm = document.getElementById('frm1'); frm.reset(); }, error: function () { $('#error').html('Error! please try with valid data.').show(); } }); } }); }); function ValidateForm() { var isAllValid = true; $('.error').hide(); $('#error').empty(); $('.form-group').removeClass('has-error'); if ($('#firstname').val().trim()=="") { $('#firstname').focus(); $('#firstname').siblings('.error').show(); $('#firstname').parents('.form-group').addClass('has-error'); isAllValid = false; } if ($('#lastname').val().trim() == "") { $('#lastname').focus(); $('#lastname').siblings('.error').show(); $('#lastname').parents('.form-group').addClass('has-error'); isAllValid = false; } if ($('#email').val().trim() != "") { var expr = /^([a-zA-Z0-9_\-\.]+)@@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/; if (!expr.test($('#email').val().trim())) { $('#email').focus(); $('#email').siblings('.error').show(); $('#email').parents('.form-group').addClass('has-error'); isAllValid = false; } } return isAllValid; } </script>Complete View
@{ ViewBag.Title = "Part3"; } <style> .error, #error { color:red; display:none; } </style> <h2>Part3 - Post data to Web API using Jquery.</h2> <div class="container1"> <form id="frm1" role="form" style="max-width:500px"> <div class="form-group"> <div id="error"> </div> </div> <div class="form-group"> <label for="firstname">First Name:</label> <input type="text" class="form-control" id="firstname"> <span class="error">Please provide First Name</span> </div> <div class="form-group"> <label for="lastname">Last Name:</label> <input type="text" class="form-control" id="lastname"> <span class="error">Please provide Last Name</span> </div> <div class="form-group"> <label for="email">Email:</label> <input type="text" class="form-control" id="email"> <span class="error">Invalid email ID</span> </div> <div class="form-group"> <label for="city">City:</label> <input type="text" class="form-control" id="city"> </div> <div class="form-group"> <label for="country">Country:</label> <input type="text" class="form-control" id="country"> </div> <button type="submit" class="btn btn-default">Submit</button> </form> </div> @section Scripts{ <script> $(document).ready(function () { var apiBaseUrl = "http://localhost:1963/"; $('#frm1').submit(function (e) { e.preventDefault(); var isOK = ValidateForm(); if (isOK) { var emp = { EmployeeID: 0, FirstName: $('#firstname').val().trim(), LastName: $('#lastname').val().trim(), EmailID: $('#email').val().trim(), City: $('#city').val().trim(), Country: $('#country').val().trim() }; //Save $.ajax({ url: apiBaseUrl+'api/example', type: 'POST', dataType: 'json', data: emp, success: function (d) { alert('Successfully Saved!'); var frm = document.getElementById('frm1'); frm.reset(); }, error: function () { $('#error').html('Error! please try with valid data.').show(); } }); } }); }); function ValidateForm() { var isAllValid = true; $('.error').hide(); $('#error').empty(); $('.form-group').removeClass('has-error'); if ($('#firstname').val().trim()=="") { $('#firstname').focus(); $('#firstname').siblings('.error').show(); $('#firstname').parents('.form-group').addClass('has-error'); isAllValid = false; } if ($('#lastname').val().trim() == "") { $('#lastname').focus(); $('#lastname').siblings('.error').show(); $('#lastname').parents('.form-group').addClass('has-error'); isAllValid = false; } if ($('#email').val().trim() != "") { var expr = /^([a-zA-Z0-9_\-\.]+)@@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/; if (!expr.test($('#email').val().trim())) { $('#email').focus(); $('#email').siblings('.error').show(); $('#email').parents('.form-group').addClass('has-error'); isAllValid = false; } } return isAllValid; } </script> }
Step-6: Run Application.
Here we need to start both application as the client application will consume services from web api application.Download View Demo