Part 3 - How to post data with validation in the ASP.NET Web API using Jquery


Introduction

In this post, I am going to explain How to post data with validation in the ASP.NET Web API using Jquery
In 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


This post is 3rd part of a series called Getting Started with ASP.NET WEB API
  1. Part1 - How to retrieve data from the database in the ASP.NET Web API using Jquery
  2. Part 2 - How to retrieve data from the database in the ASP.NET Web API using Http Client
  3. Part 3 - How to post data with validation in the ASP.NET Web API using Jquery
  4. Part 4 - How to post data with validation in the ASP.NET Web API using Http Client
  5. Part 5 - How to upload files in the ASP.NET Web API using Jquery
  6. Part 6 - How to upload files in the ASP.NET Web API using Http Client
  7. 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.cs
    namespace 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">&nbsp;</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">&nbsp;</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
Part 3 - How to post data with validation in the ASP.NET Web API using Jquery

Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.