Sunday, August 24, 2014

Working with Json Objects using Ajax and Asp.Net Mvc 4

Working with Json Objects using Ajax and Asp.Net Mvc 4

In this article, I’m explaining how to work with json objects and how to pass the json objects in the view using ajax and asp.net mvc 4.


JSON stands for JavaScript Object Notation. JSON is a light-weight text based format for data exchange. Using JSON format you can pack the data that needs to be transferred between the client and the server.
Using JSON format you essentially represent objects. In that respect JSON is quite similar to JavaScript objects. However, it is important to remember that although JavaScript objects and JSON objects look quite similar these two formats are not exactly the same.

Example

In this example, we going to create an asp.net mvc application and we will have one 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 json objects and in the second portion – we have product list, where we will display the products from the database using the json objects.

Step 1

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




Step 2

First create a basic asp.net mvc 4 application and add a class named “Product”, 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 JsonObjectMvcApp.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 3

Now add another class named “ProductEntities” and write below code in it:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

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




Step 4

Now add a controller named “HomeController” to the project and write the below code in it:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using JsonObjectMvcApp.Models;

namespace JsonObjectMvcApp.Controllers
{
    public class HomeController : Controller
    {
        ProductEntities db = new ProductEntities();

        public ActionResult Index()
        {
            return View();
        }

       
        public JsonResult PostForm(Product product)
        {
            if (ModelState.IsValid)
            {
                db.Products.Add(product);
                db.SaveChanges();
               
            }
            return Json(product);
        }

        public JsonResult getProductList()
        {
            return Json(db.Products.ToList(), JsonRequestBehavior.AllowGet);
        }

    }
}



Step 4

Now add a view named “Index” and write the below code in it:
@{
    ViewBag.Title = "Index";
}


<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script>
    $(function () {

        $.ajax({
            type: "GET",
            url: "/home/getproductlist/",
            datatype: "Json",
            success: function (data) {
                if (data != null) {
                    $.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("home/postform", Product, success = function (data) {
                $('#ProductList').append('<li>' + data.Name + " : " + data.Category + " :  $" + data.Price + '</li>');
            });

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

    });

</script>

<div>
    <fieldset style="width:500px;">
        <legend>Product Form</legend>
        <div style="width: 100%; ">
            <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>
        </div>
    </fieldset>

    <fieldset style="width:500px;">
        <legend>Product Records List</legend>
        <ul id="ProductList">

        </ul>
    </fieldset>
</div>


Step 5

Now add the connection string in the 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 can see that there are records in the product list; it has come from the table “Product” using the json object and ajax call.


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



You can see that – as soon as you click on submit button, the record is 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