Create Shopping Cart In MVC using Ajax and Jquery

This Tutorial will show how to create shopping cart in MVC using Jquery and Ajax.

In previous artilce I have shown How to create login and Registration page in MVC
Step 1- Create a new Empty MVC project.
Step 2- Add the following class to your model folder.

public class Item
    {
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
        public int Price { get; set; }
        public string Description { get; set; }
        public string Category { get; set; }
        public int Offer { get; set; }
        public string ImagePath { get; set; }
    }

    public class Cart
    {
        [Key]
        public int Id { get; set; }
        public string UserName { get; set; }
        public int ItemId { get; set; }
    }

    public class Login
    {
        [Key]
        public int Id { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
    }

Step 3- Add Context Class.

using System.Data.Entity;

namespace ShopingCartDemo.Models
{
    public class DemoContext : DbContext
    {
        public DbSet<Item> Item { get; set; }
        public DbSet<Cart> Cart { get; set; }
        public DbSet<Login> Login { get; set; }
    }
}

Step 4- Build your solution then add Home Controller . Here I have Created Login page . To know more about how to create login page see previous artilcel. Create Login Page In MVC
Step 5- Add the following code to your Controller .

using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using ShopingCartDemo.Models;
namespace ShopingCartDemo.Controllers
{
    public class HomeController : Controller
    {
        DemoContext dbObj = new DemoContext();
        public ActionResult Index()
        {
            if (Session["username"] == null)
            {
                return RedirectToAction("login");
            }
            else
            {
                string getName = Session["username"].ToString();
                ViewBag.userName = getName;
                int count = dbObj.Cart.Where(s => s.UserName == getName).Count();
                ViewBag.cartCount = count;
                return View("Index", getAllItems());
            }

        }

        [HttpGet]
        public ActionResult Login()
        {
            Session["username"] = null;
            return View("login");
        }

        [HttpPost]
        public ActionResult Login(Login objLogin)
        {
            var getValidUser = dbObj.Login.FirstOrDefault((p) => p.UserName == objLogin.UserName && p.Password == objLogin.Password);
            if (getValidUser != null)
            {
                Session["username"] = objLogin.UserName;
                return RedirectToAction("Index");
            }
            else
            {
                ViewBag.LoginFaild = "Invalid username or password";
                return View("login");
            }
        }

        public IList<Item> getAllItems()
        {
            IList<Item> items = new List<Item>();
            items = dbObj.Item.ToList();
            return items;
        }

        public int AddCart(int ItemId)
        {
            string username = Session["username"].ToString();
            Cart objcart = new Cart()
            {
                UserName = username,
                ItemId = ItemId
            };
            dbObj.Cart.Add(objcart);
            dbObj.SaveChanges();
            int count = dbObj.Cart.Where(s => s.UserName == username).Count();
            return count;
        }


        public PartialViewResult GetCartItems()
        {
            string username = Session["username"].ToString();
            var sum = 0;
            var GetItemsId = dbObj.Cart.Where(s => s.UserName == username).Select(u => u.ItemId).ToList();
            var GetCartItem = from itemList in dbObj.Item where GetItemsId.Contains(itemList.Id) select itemList;
            foreach (var totalsum in GetCartItem)
            {
                sum = sum + totalsum.Price;
                sum = sum - ((totalsum.Price * totalsum.Offer) / 100);
            }
            ViewBag.Total = sum;
            return PartialView("_cartItem", GetCartItem);

        }

        public PartialViewResult DeleteCart(int itemId)
        {
            string getName = Session["username"].ToString();
            Cart removeCart = dbObj.Cart.FirstOrDefault(s => s.UserName == getName && s.ItemId == itemId);
            dbObj.Cart.Remove(removeCart);
            dbObj.SaveChanges();
            return GetCartItems();
        }
    }
}

Step 6- Add a strolngly typed view INDEX. which will show list of Items and Cart count. Add the following code to Index View.

@model IEnumerable<ShopingCartDemo.Models.Item>

<script src="../../Scripts/jquery-2.1.1.js" type="text/javascript"></script>
<script src="~/Scripts/bootstrap-modal.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<link href="../../Content/Style.css" rel="stylesheet" type="text/css" />


<script>
    $(document).ready(function () {

        $('.divAddCart').on('click', function () {
            var getItemId =parseInt($(this).closest('td').prop('id'));
            var getUserName = $('.divName').html();
            $.ajax({
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                url: 'Home/AddCart',
                data: "{ 'itemId':' " + getItemId + "' }",
                success: function (data) {
                    $('#spnCart').html(data)
                },
                error: function (data) {
                    alert(data);
                }
            });
        });

        $('#spnCart').on('click', function () {
            var getName = $('.divName').html();
            $.ajax({
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                url: '/Home/GetCartItems',
               
                success: function (data) {
                    $('#exampleModal').html(data);
                    $('#exampleModal').modal({
                        backdrop:false
                    });
                },
                error: function (data) {
                    alert(data);
                }
            });
        });

        $(document).delegate('.cartDel', 'click', function () {
            var DeleteItem=parseInt($(this).closest('tr').prop('id'));
            $.ajax({
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                url: '/Home/DeleteCart',
                data: "{ 'itemId':' " + DeleteItem + "' }",
                success: function (data) {
                    $('#exampleModal').html(data);
                    $('#spnCart').html($(data).find('#cartList tbody tr').length);
                    $('#exampleModal').modal({
                        backdrop: false
                    });
                },
                error: function (data) {
                    alert(data);
                }
            });
        });
    });
</script>
<div class="top">
    <div class="divName">@ViewBag.userName</div>
    <div class="divCart">
        Total Items In Cart : <span id="spnCart">@ViewBag.cartCount</span>
    </div>
    <div class="divLgout">
        @Html.ActionLink("Logout","Login")
    </div>
    <div class="container">
    <table>
        @foreach (var objItem in Model)
        {
            <tr>
                <td id="@objItem.Id">
                    <div class="itemImage">
                        <div class="divImg"><img src="@objItem.ImagePath" height="150" width="150" /></div>
                        <div class="divIName">@objItem.Name</div>
                    </div>
                    <div class="itemDetails">
                        <div class="divDesc">@objItem.Description</div>
                        <div class="divCat">Category : @objItem.Category</div>
                        <div class="divPrice">Price : @objItem.Price</div>
                        <div class="divOff">Off : @objItem.Offer %</div>
                        <div class="divBuy">Buy</div>
                        <div class="divAddCart">Add To Cart</div>
                    </div>
                </td>
            </tr>
        }
    </table>
    </div>
</div>

<div class="modal" id="exampleModal" tabindex="1000" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">

</div>

Step 7- To Added Cart Item Popup, I have created a partial view , which will render on click of Total Number of item in cart . Create a partial view _cartItem, then add the following code to this partial view.

@model IEnumerable<ShopingCartDemo.Models.Item>
<div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">
                <span aria-hidden="true">×</span><span class="sr-only">Close</span>
            </button>
            <h4 class="modal-title" id="myModalLabel">
                Your cart
            </h4>
        </div>
        <div class="modal-body">
            <table id="cartList">
                <thead>
                    <tr>
                        <td><b>Image</b></td>
                        <td><b>Name</b></td>
                        <td><b>Price</b></td>
                        <td><b>Offer</b></td>
                        <td><b>Action</b></td>
                    </tr>
                </thead><tbody>
    @foreach (var objItem in Model)
    {

        <tr id="@objItem.Id">
            <td>
                <img src="@objItem.ImagePath" width="50" height="50" />
            </td>
            <td>
                @objItem.Name
            </td>
            <td>
                @objItem.Price
            </td>
            <td>
                @objItem.Offer

            </td>
            <td>
                <span class="cartDel">Remove</span>
            </td>
        </tr>
    }
</tbody>

            </table>
            <span class="totalPrice">Total Amount @ViewBag.Total</span>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">
                Close
            </button>
            <button type="button" class="btn btn-primary">
                Proceed
            </button>
        </div>
    </div>
</div>

DEMO
Create Shopping Cart In MVC | Create Shopping Cart In ASP using ajax and jquery

Download

Library Management System In Asp.Net

Library Management System In Asp.Net and C#

This Library Management System for Library developed in Asp.Net and C#, Javascript, Ajax. Using sql server as database.
This Project have 3 type of users.
1- Admin
2- Library User
3- Common user
According to their role, Their task and rights are different.
Admin

  1. Add new books.
  2. Issues requested books.
  3. Restore returned books
  4. View and delete users.
  5. Assign roles.
  6. Generate PDF and Excel report.

Library User

  1. Register, Login, Add Details.
  2. Search books.
  3. Request for books
  4. Request for delete account.

Common Users

  1. Search books
  2. Give feedback.

Admin Username and Password
Username: amit
password: amit@123

DEMO
Library Management System

Download

How to save records using Ajax and Jquery in Asp.Net

This article will show you how to save data records using Ajax and Jquey.

Step 1- Create a new Empty Web Site.
Step 2- Add a new Web Form.
Step 3-Write down the following code to you Web Fom.

<form id="form1" runat="server">
     <div>
        <table>
            <tr>
                <td>
                    Name
                </td>
                <td>
                    <input type="text" id="txtName" />
                </td>
            </tr>
            <tr>
                <td>
                    Position
                </td>
                <td>
                    <input type="text" id="txtPosition" />
                </td>
            </tr>
            <tr>
                <td>
                    Age
                </td>
                <td>
                    <input type="text" id="txtAge" />
                </td>
            </tr>
            <tr>
                <td>
                    Salary
                </td>
                <td>
                    <input type="text" id="txtSalary" />
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <input type="button" onclick="SaveData();" value="Save" />
                </td>
            </tr>
        </table>
    </div>
    </form>

Write down the following Js code.

function SaveData() {
            var errMsg = '';
            var name = $('#txtName').val().trim();
            var position = $('#txtPosition').val().trim();
            var age = parseInt($('#txtAge').val().trim());
            var salary = parseInt($('#txtSalary').val().trim());
            $.ajax({
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                url: 'Index.aspx/SaveData',
                data: "{ 'Name':' " + name + "', 'Position':' " + position + "', 'Age':' " + age + "', 'Salary':' " + salary + "' }",
                success: function (data) {
                    alert(data.d);
                    clearAll();
                },
                error: function (data) {
                    alert(data.d);
                }
            });
        }
        function clearAll() {
            $('#txtName').val('');
            $('#txtPosition').val('');
            $('#txtAge').val('');
            $('#txtSalary').val('');
        }

Add a static Web Method to Code behind file .

[WebMethod]
    public static string SaveData(string Name, string Position, int Age, int Salary)
    {
        string str = ConfigurationManager.ConnectionStrings["connect"].ConnectionString;
        string msg = "";
        try
        {
            SqlConnection con = new SqlConnection(str);
            con.Open();
            SqlCommand cmd = new SqlCommand("insert into Employee values (@1,@2,@3,@4)", con);
            cmd.Parameters.Add("@1", Name);
            cmd.Parameters.Add("@2", Position);
            cmd.Parameters.Add("@3", Age);
            cmd.Parameters.Add("@4", Salary);
            cmd.ExecuteNonQuery();
            con.Close();
            msg = "Record Inserted";
        }
        catch (Exception ex)
        {
            msg = "Record Not Inserted" + ex.Message;
        }

        return msg;
    }

DEMO
Crud Operation In Asp.Net Using Ajax and Jqery

Download

Create AutoComplete Extender In Asp.Net Wcf using Ajax and Jquery

In this article I’ll explain how to create AutoComplete Extender In Asp.Net Using WCF.

Step 1- Create a Empty Web Application.
Step 2- Add WCF Service to your Project. In Previous article I have explained how to use WCF Service with ajax and jquery.
Step 3- Write the following code to your Service Class .

using System;
using System.Collections.Generic;
using System.Linq;
using System.Configuration;
using System.Data.SqlClient;
using System.ServiceModel.Activation;
using System.Web.Script.Serialization;

namespace AjaxAndWcfDemo
{
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Service : IService
    {
       
        public List<string> FindEmployees(string empName)
        {
            string str = ConfigurationManager.ConnectionStrings["Connect"].ConnectionString;
            IList<string> NameList = new List<string>();
            using (SqlConnection con = new SqlConnection(str))
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("select * from Employee where Name LIKE '%" + empName + "%'", con);
                SqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    NameList.Add(dr.GetString(1));
                }
                con.Close();
            }
            return NameList.ToList();
        }
    }
}

Add the following code to IService Interface

using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
namespace AjaxAndWcfDemo
{
    [ServiceContract]
    public interface IService
    {
        [OperationContract]
        [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]
        List<string> FindEmployees(string empName);
    }

    [DataContract]
    public class Employee
    {
        [DataMember]
        public int Id { get; set; }
        [DataMember]
        public string Name { get; set; }
        [DataMember]
        public string Position { get; set; }
        [DataMember]
        public int Age { get; set; }
        [DataMember]
        public int Salary { get; set; }
    }
}

Step 4- Add a Web Form and add a textbox to it.

<div>
     Employee Name :   <input type="text" id="txtEmployee" /> 
   </div>

Step 5- Add Jquery Library and Css file to project .
You can download jquery file from here Download Or Right click on Solution then click Manage Nuget Packages , Type Jquery in search box. Install 1- Jquery and 2- Jquery UI(Combined Library).

Step 6- Add the followng js code.

<script>
        $(document).ready(function () {
            $("#txtEmployee").autocomplete({
                source: function (request, response) {
                    var objEname = { empName: $('#txtEmployee').val() };
                    $.ajax({
                        url: "Service.svc/FindEmployees",
                        data: JSON.stringify(objEname),
                        dataType: "json",
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        dataFilter: function (data) { return data; },
                        success: function (data) {
                            response($.map(data.d, function (item) {
                                return {
                                    value: item
                                }
                            }))
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(textStatus);
                        }
                    });
                },
                minLength: 2
            });
        });
    </script>

Know more about AutoComplete Extender Examples See This Tutorial
DEMO
AutoComplete Extender In Asp.Net Using WCF and Ajax | Create AutoComplete Extender In Asp.Net Web Services using Ajax

DownLoad

Ajax call Asp.Net WCF Service using Jquery

This Article will show you, how to make Ajax call to wcf service using jquery

Step 1- Create a empty web application.
Step 2- Add Wcf Service to your porject. It will add default IService interface and Service class to your project.
IService will contain Service contract and Data contract. where as Service call is inherited by IService inteface.
Step 3- Add the following code to IService interface.

using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
namespace AjaxAndWcfDemo
{
    [ServiceContract]
    public interface IService
    {
        [OperationContract]
        [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]
        string GetEmployee();
    }

    [DataContract]
    public class Employee
    {
        [DataMember]
        public int Id { get; set; }
        [DataMember]
        public string Name { get; set; }
        [DataMember]
        public string Position { get; set; }
        [DataMember]
        public int Age { get; set; }
        [DataMember]
        public int Salary { get; set; }
    }
}

You can see I have added WebInvoke attribute to method to specify, which will invoke Http Request and Response in json formate.
Step 4- Add the following code to Service class.

using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.ServiceModel.Activation;
using System.Web.Script.Serialization;

namespace AjaxAndWcfDemo
{
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Service : IService
    {
        public string GetEmployee()
        {
            string str = ConfigurationManager.ConnectionStrings["Connect"].ConnectionString;
            IList<Employee> employeeList = new List<Employee>();
            using (SqlConnection con = new SqlConnection(str))
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("select * from Employee", con);
                SqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    employeeList.Add(new Employee()
                    {
                        Id = dr.GetInt32(0),
                        Name = dr.GetString(1),
                        Position = dr.GetString(2),
                        Age = dr.GetInt32(3),
                        Salary = dr.GetInt32(4)
                    });
                }

                con.Close();
            }
            JavaScriptSerializer jsonEmployee = new JavaScriptSerializer();
            return jsonEmployee.Serialize(employeeList);
        }
    }
}

AspNetCompatibilityRequirements attribute will make the WCF Service behave like Asp.Net ASMX Web Service and able to process Request via Http.
Step 6- Now write the following code to web.config file.

<system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="ServiceAspNetAjaxBehavior">
          <enableWebScript/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
    <services>
      <service behaviorConfiguration="ServiceBehavior" name="AjaxAndWcfDemo.Service">
        <endpoint address="" binding="webHttpBinding" contract="AjaxAndWcfDemo.IService" behaviorConfiguration="ServiceAspNetAjaxBehavior">
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint>
      </service>
    </services>
  </system.serviceModel>

Step 7- Add a web form, And write the following code.

<head runat="server">
    <script src="Js/jquery-2.1.1.min.js"></script>
    <script>
        $(document).ready(function () {
            $('.getRecord').on('click', function () {
                $.ajax({
                    type: 'POST',
                    contentType: 'application/json;charset=utf-8',
                    url: 'Service.svc/GetEmployee',
                    datatype: "json",
                    success: function (data) {
                        BindTable(data.d);
                    },
                    error: function (data) {
                        alert('Error in getting employee');
                    }
                });
            });
        });
        function BindTable(objEmployees) {

            var tableHtml = '';
            $.each($.parseJSON(objEmployees), function (key, val) {
                tableHtml += '"<tr><td>' + val.Name + '</td><td>' + val.Position + '</td>"' +
                             '<td>' + val.Age + '</td><td>' + val.Salary + '</td></tr>';
            });
            $('#tblList').find('tbody').html(tableHtml);
            $('#tblList').fadeIn('slow');
        }
    </script>
    <title>Index</title>

    <style>
        .getRecord{
            background:green;
            color:white;
            padding:5px;
            border-radius:2px;
            cursor:pointer;
        }
        .divContent{
            margin:40px;
        }
        #tblList{
            border: 1px solid;
          margin-top: 22px;
          display:none;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div class="divContent">
        <span class="getRecord">Get Employees</span>
        <table id="tblList" cellpadding="7">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Position</th>
                    <th>Age</th>
                    <th>Salary</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
    </div>
    </form>
</body>

DEMO
Make Ajax Json call to wcf using jquery and javascript.

Download