Create Web API in ASP.Net C# with SQL Server Database

Database:

The Customers table, which I used, has the following schema. CustomerId is an auto-increment (identity) column.

Entity Framework Model:

Once the Entity Framework has been configured and connected to the database table, the Model will display as seen below.

Controller:

The Controller includes the action method listed below, which handles the GET operation.
Within this Action method, every entry from the Customers table is returned to the View as a Generic List collection..
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        CustomersEntities entities = new CustomersEntities();
        List<Customer> customers = entities.Customers.ToList();
        if (customers.Count == 0)
        {
            customers.Add(new Customer());
        }
 
        return View(customers);
    }
}

Web API Controller:

The Web API Controller is made up of the next three Action methods.
the steps for inserting
Inside of this Action method, the received Customer object is added to the Customers table. The changed Customer object, together with the generated Customer Id, is then returned to the jQuery AJAX function that called it.

Method for Updating
This Action function receives the Customer object as an input. The CustomerId value of the receiving Customer object is used to refer to the Customer record in the Customer Entities.
After the record is accessed, the Name and Country values are changed, and the Customer table is updated to reflect the changes.

The method for deletion
This Action function receives the CustomerId value as an argument. As a pointer, the CustomerId value is used.

public class AjaxAPIController : ApiController
{
    [Route("api/AjaxAPI/InsertCustomer")]
    [HttpPost]
    public Customer InsertCustomer(Customer _customer)
    {
        using (CustomersEntities entities = new CustomersEntities())
        {
            entities.Customers.Add(_customer);
            entities.SaveChanges();
        }
 
        return _customer;
    }
 
    [Route("api/AjaxAPI/UpdateCustomer")]
    [HttpPost]
    public bool UpdateCustomer(Customer _customer)
    {
        using (CustomersEntities entities = newCustomersEntities())
        {
            Customer updatedCustomer = (from c in entities.Customers
                                        where c.CustomerId == _customer.CustomerId
                                        select c).FirstOrDefault();
            updatedCustomer.Name = _customer.Name;
            updatedCustomer.Country = _customer.Country;
            entities.SaveChanges();
        }
 
        return true;
    }
 
    [Route("api/AjaxAPI/DeleteCustomer")]
    [HttpPost]
    public void DeleteCustomer(Customer _customer)
    {
        using (CustomersEntities entities = new CustomersEntities())
        {
            Customer customer = (from c in entities.Customers
                                 where c.CustomerId == _customer.CustomerId
                                 select c).FirstOrDefault();
            entities.Customers.Remove(customer);
            entities.SaveChanges();
        }
   }
}

View:

The very first line of the view declares the Entity Framework Customer Model class as its model.
Display
HTML tables are used to display the records. To create the rows of the HTML Table containing the Customer records, the Model will be iterated over in a loop.

Insert
When the Add button is clicked, the name and the country information are retrieved from the appropriate TextBoxes and given to the InsertCustomer Action function via a jQuery AJAX request.
The AppendRow function of the HTML table inserts a new row after the response has been received.

Edit
When the Edit button is pressed, which establishes the reference of the HTML Table row, the HTML SPAN components are rendered invisible while the TextBoxes in the Name and Country columns of the HTML Table become visible.
Update
The new values for the Name and Country columns are retrieved from the appropriate TextBoxes when the Update Button is clicked, and the CustomerId is retrieved from the HTML SPAN element of the CustomerId column.
Using a jQuery AJAX call, the values of CustomerId, Name, and Country are supplied to the UpdateCustomer Action function.
The HTML SPAN elements are made visible and the TextBoxes are made hidden for the Name and Country columns of the HTML Table row once the response has been received.

Cancel
When the Cancel button is pressed, the HTML Table row’s reference is identified, the HTML SPAN elements are made visible, and the TextBoxes in the Name and Country columns of the HTML Table row are made hidden.

Delete
The CustomerId value is obtained and supplied to the DeleteCustomer Action method via a jQuery AJAX request when the Delete Button is hit, determining the reference of the HTML Table row.
After receiving a response, the corresponding row is deleted from the HTML Table row.

@model IEnumerable<jQuery_AJAX_WebAPI_CRUD_MVC.Customer>
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    <table id="tblCustomers" class="table" cellpadding="0" cellspacing="0">
        <tr>
            <th style="width:100px">Customer Id</th>
            <th style="width:150px">Name</th>
            <th style="width:150px">Country</th>
            <th style="width:150px"></th>
        </tr>
        @foreach (Customer customer in Model)
        {
            <tr>
                <td class="CustomerId">
                    <span>@customer.CustomerId</span>
                </td>
                <td class="Name">
                    <span>@customer.Name</span>
                    <input type="text" value="@customer.Name" style="display:none"/>
                </td>
                <td class="Country">
                    <span>@customer.Country</span>
                    <input type="text" value="@customer.Country" style="display:none"/>
                </td>
                <td>
                    <a class="Edit" href="javascript:;">Edit</a>
                    <a class="Update" href="javascript:;" style="display:none">Update</a>
                    <a class="Cancel" href="javascript:;" style="display:none">Cancel</a>
                    <a class="Delete" href="javascript:;">Delete</a>
                </td>
            </tr>
        }
    </table>
    <table border="0" cellpadding="0" cellspacing="0">
        <tr>
            <td style="width: 150px">
                Name<br/>
                <input type="text" id="txtName" style="width:140px"/>
            </td>
            <td style="width: 150px">
                Country:<br/>
                <input type="text"id="txtCountry" style="width:140px"/>
            </td>
            <td style="width: 200px">
                <br/>
                <input type="button" id="btnAdd" value="Add"/>
            </td>
        </tr>
    </table>
 
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
    <script type="text/javascript">
        $(function () {
            //Remove the dummy row if data present.
            if ($("#tblCustomers tr").length > 2) {
                $("#tblCustomers tr:eq(1)").remove();
            } else {
                var row = $("#tblCustomers tr:last-child");
                row.find(".Edit").hide();
                row.find(".Delete").hide();
                row.find("span").html('&nbsp;');
            }
        });
        function AppendRow(row, customerId, name, country) {
            //Bind CustomerId.
            $(".CustomerId", row).find("span").html(customerId);
 
            //Bind Name.
            $(".Name", row).find("span").html(name);
            $(".Name", row).find("input").val(name);
 
            //Bind Country.
            $(".Country", row).find("span").html(country);
            $(".Country", row).find("input").val(country);
 
            row.find(".Edit").show();
            row.find(".Delete").show();
 
            $("#tblCustomers").append(row);
        };
 
        //Add event handler.
        $("body").on("click", "#btnAdd", function () {
            var txtName = $("#txtName");
            var txtCountry = $("#txtCountry");
            var _customer = {};
            _customer.Name = txtName.val();
            _customer.Country = txtCountry.val();
            $.ajax({
                type: "POST",
                url: "/api/AjaxAPI/InsertCustomer",
                data: JSON.stringify(_customer),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (r) {
                    var row = $("#tblCustomers tr:last-child");
                    if ($("#tblCustomers tr:last-child span").eq(0).html() != "&nbsp;") {
                        row = row.clone();
                    }
                    AppendRow(row, r.CustomerId, r.Name, r.Country);
                    txtName.val("");
                    txtCountry.val("");
                }
            });
        });
 
        //Edit event handler.
        $("body").on("click", "#tblCustomers .Edit", function () {
            var row = $(this).closest("tr");
            $("td", row).each(function () {
                if ($(this).find("input").length > 0) {
                    $(this).find("input").show();
                    $(this).find("span").hide();
                }
            });
            row.find(".Update").show();
            row.find(".Cancel").show();
            row.find(".Delete").hide();
            $(this).hide();
        });
 
        //Update event handler.
        $("body").on("click", "#tblCustomers .Update", function () {
            var row = $(this).closest("tr");
            $("td", row).each(function () {
                if ($(this).find("input").length > 0) {
                    var span = $(this).find("span");
                    var input = $(this).find("input");
                    span.html(input.val());
                    span.show();
                    input.hide();
                }
            });
            row.find(".Edit").show();
            row.find(".Delete").show();
            row.find(".Cancel").hide();
            $(this).hide();
            var _customer = {};
            _customer.CustomerId = row.find(".CustomerId").find("span").html();
            _customer.Name = row.find(".Name").find("span").html();
            _customer.Country = row.find(".Country").find("span").html();
            $.ajax({
                type: "POST",
                url: "/api/AjaxAPI/UpdateCustomer",
                data: JSON.stringify(_customer),
                contentType: "application/json; charset=utf-8",
                dataType: "json"
            });
        });
 
        //Cancel event handler.
        $("body").on("click", "#tblCustomers .Cancel", function () {
            var row = $(this).closest("tr");
            $("td", row).each(function () {
                if ($(this).find("input").length > 0) {
                    var span = $(this).find("span");
                    var input = $(this).find("input");
                    input.val(span.html());
                    span.show();
                    input.hide();
                }
            });
            row.find(".Edit").show();
            row.find(".Delete").show();
            row.find(".Update").hide();
            $(this).hide();
        });
 
        //Delete event handler.
        $("body").on("click", "#tblCustomers .Delete", function () {
            if (confirm("Do you want to delete this row?")) {
                var row = $(this).closest("tr");
                var _customer = {};
                _customer.CustomerId = row.find("span").html();
                $.ajax({
                    type: "POST",
                    url: "/api/AjaxAPI/DeleteCustomer",
                    data: JSON.stringify(_customer),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        if ($("#tblCustomers tr").length > 2) {
                            row.remove();
                        } else {
                            row.find(".Edit").hide();
                            row.find(".Delete").hide();
                            row.find("span").html('&nbsp;');
                        }
                    }
                });
            }
        });
    </script>
</body>
</html>

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories