Sunday, August 24, 2014

Calling Asp.Net Web API methods from Jquery in Asp.Net Mvc 4

Calling Asp.Net Web API methods from Jquery in Asp.Net Mvc 4

In this article, I’m explaining how to call the asp.net web api methods from jquery in asp.net mvc 4.


If you want to learn crud in asp.net mvc web api, then you can read my blog:

http://sumitkesarwani.blogspot.in/2014/08/crud-operation-using-aspnet-mvc-web-api.html



Example

In this example, we will create an asp.net web api project and we will have a view in it called “Index”. Index view will have two portions – first is a product form, where we put the values in the textboxes and save it in database using the web api method and in the second portion – we have product list, where we will display the products from the database using the web api method.

Step 1

First create an asp.net mvc 4 application like this:






Step 2

Create a table in the database named “Product” like this:






Step 3

Add a class named “Product” to the project and write the below code in it:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace AspNetWebApiWithJquery.Models
{
    [Table("Product")]
    public class Product
    {
        [Key]
        public int ProductId { get; set; }
        public string Name { get; set; }
        public string Category { get; set; }
        public string Price { get; set; }
    }

}




Step 4

Add another class named “ProductEntities” to the project like this:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace AspNetWebApiWithJquery.Models
{
    public class ProductEntities : DbContext
    {
        public DbSet<Product> Products { get; set; }
    }

}

 


Step 5

Change the code of the “ValuesController” like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Mvc;
using AspNetWebApiWithJquery.Models;

namespace AspNetWebApiWithJquery.Controllers
{
    public class ValuesController : ApiController
    {
        ProductEntities db = new ProductEntities();

        // GET api/values
        public IEnumerable<Product> Get()
        {
            return db.Products.ToList();
        }

      

        // POST api/values
        public Product Post(Product product)
        {
            if (ModelState.IsValid)
            {
                db.Products.Add(product);
                db.SaveChanges();
            }
            return product;
        }

       
    }

}

 


Step 6

Now changed the code of “HomeController”  like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace AspNetWebApiWithJquery.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    }
}

 

 

Step 7

Add changed the code of “Index” view like this:
<html>
<head>
    <title>Calling Asp.Net Web API Methods From JQuery
    </title>
    <script src="~/Scripts/jquery-1.7.1.min.js"></script>
    <script>
        $(function () {

            $.getJSON("api/Values", function (data) {
                $.each(data, function (index, value) {
                    $('#ProductList').append('<li>' + value.Name + " : " + value.Category + " :  $" + value.Price + '</li>');
                });
            });

            $('#btnSubmit').click(function () {
                var Product = new Object();
                Product.Name = $('#txtProductName').val();
                Product.Category = $('#txtProductCategory').val();
                Product.Price = $('#txtProductPrice').val();

                $.post("api/Values", Product, success = function (data) {
                    $('#ProductList').append('<li>' + data.Name + " : " + data.Category + " :  $" + data.Price + '</li>');
                });

                $('#txtProductName').val('');
                $('#txtProductCategory').val('');
                $('#txtProductPrice').val('');

            });
        });
    </script>
</head>

<body>
    <div>
        <fieldset style="width:500px;">
            <legend>Product Form</legend>
            <div style="width: 100%; float: left;">
                <div style="width: 200px; float: left;">
                    <label>Product Name : </label>
                </div>
                <div style="width: 200px; float: left;">
                    <input type="text" id="txtProductName" />
                </div>
            </div>
            <div style="width: 100%; float: left;">
                <div style="width: 200px; float: left;">
                    <label>Product Category : </label>
                </div>
                <div style="width: 200px; float: left;">
                    <input type="text" id="txtProductCategory" />
                </div>
            </div>
            <div style="width: 100%; float: left;">
                <div style="width: 200px; float: left;">
                    <label>Product Price : </label>
                </div>
                <div style="width: 200px; float: left;">
                    <input type="text" id="txtProductPrice" />
                </div>
            </div>
            <div style="width: 100%; float: left;">
                <div style="width: 205px; float: right;">
                    <input type="button" id="btnSubmit" value="Submit" />
                </div>
            </div>
        </fieldset>

        <fieldset style="width:500px;margin-top:30px;">
            <legend>Product Records List</legend>
            <ul id="ProductList"></ul>
        </fieldset>
    </div>
</body>
</html>




Step 8

Now add the connection string in web.config file like this:
<connectionStrings>
   
    <add name="ProductEntities" connectionString="Data Source=DELL-PC\SQLEXPRESS;Initial Catalog=sumit_db;Integrated Security=true;" providerName="System.Data.SqlClient"/>
  </connectionStrings>




Now your Solution explorer will look like this:






Output

Now run the application:





You will see that the product list is being populated from the database:

Now fill the form with the desired values and click on submit button:






You will see that your new record is being added to the product list.





Thank you for reading this article, please put your valuable comment or any suggestion/question in the comment box.

No comments:

Post a Comment