Live Traffic Feed

Saturday, July 4, 2015

angularjs grid with sorting,searching and paging functionality in asp.net C#

Leave a Comment
First you have to download angular.min.js file from official site of angular js https://angularjs.org/

create one grid.aspx page like:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="~/Grid.aspx.cs" Inherits="First.Grid" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.1.1/css/bootstrap.no-icons.min.css"
        rel="stylesheet">
    <link href="http://netdna.bootstrapcdn.com/font-awesome/2.0/css/font-awesome.css"
        rel="stylesheet">
    <script src="js/jquery-2.1.1.min.js"></script>
    <script src="js/angular.min.js"></script>
    <script src="js/grid.js"></script>
    <style type="text/css">
        .disabled
        {
            pointer-events: none !important;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div ng-controller="ctrlRead" ng-app="grid">
        <div class="input-append" style="float: right;">
            <input type="text" ng-model="query" ng-change="search()" class="input-large search-query"
                placeholder="Search">
            <span class="add-on"><i class="icon-search"></i></span>
        </div>
        <table class="table table-striped table-condensed table-hover">
            <thead column-names>
                <tr>
                    <th class="ID">
                        ID&nbsp;<a ng-click="sort_by('ID')"><i class="icon-sort"></i></a>
                    </th>
                    <th class="firstName">
                        First Name&nbsp;<a ng-click="sort_by('FirstName')"><i class="icon-sort"></i></a>
                    </th>
                    <th class="lastName">
                        Last Name&nbsp;<a ng-click="sort_by('LastName')"><i class="icon-sort"></i></a>
                    </th>
                    <th class="email">
                        Email&nbsp;<a ng-click="sort_by('email')"><i class="icon-sort"></i></a>
                    </th>
                </tr>
            </thead>
            <tfoot pager-data>
                <tr>
                    <td colspan="' + cols.length + '">
                        <div class="pagination pull-right">
                            <ul>
                                <li ng-class="{disabled: currentPage == 0}"><a href ng-click="prevPage()">« Prev</a></li>
                                <li ng-repeat="n in range(leftStart,leftStart+4)|limitTo:pagedItems.length" ng-class="{active: n == currentPage}"
                                    ng-click="setPage()"><a href ng-bind="n + 1">1</a></li>
                                <li ng-class="{disabled: pagedItems.length<(leftStart+5)}" ng-click="leftNextPages()">
                                    <a href>»</a></li>
                                <li ng-class="{disabled: pagedItems.length<(leftStart+8)}" ng-click="RightPriviousPages()">
                                    <a href>«</a></li>
                                <li ng-repeat="n in range(rightStart-3,rightStart)|limitTo:pagedItems.length-1:1"
                                    ng-class="{active: n == currentPage}" ng-click="setPage()"><a href ng-bind="n + 1">1</a></li>
                                <li ng-class="{disabled: currentPage == pagedItems.length - 1}"><a href ng-click="nextPage()">
                                    Next »</a></li></ul>
                        </div>
                    </td>
                </tr>
            </tfoot>
            <tbody cell-values>
                <tr ng-repeat="item in pagedItems[currentPage]">
                    <td>
                        {{item.ID}}
                    </td>
                    <td>
                        {{item.FirstName}}
                    </td>
                    <td>
                        {{item.LastName}}
                    </td>
                    <td>
                        {{item.Email}}
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
    </form>
</body>
</html>

Create one js file named grid.js like:
//this file is for fill grid and perform sorting,searching and paging operation.. Added by Vimal Vataliya
app = angular.module("grid", []);
sortingOrder = "FirstName";
leftStart = 0;
rightStart = 5;
app.controller("ctrlRead", createGrid);
createGrid.$inject = ['$scope', '$filter', '$http'];

function createGrid($scope, $filter, $http) {

    $scope.sortingOrder = sortingOrder;
    $scope.leftStart = leftStart;
    $scope.reverse = false;
    $scope.rightStart = rightStart;
    $scope.filteredItems = [];
    $scope.groupedItems = [];
    $scope.itemsPerPage = 15;
    $scope.pagedItems = [];
    $scope.currentPage = 0;
    $http.post("WSTest.asmx/getBulkRecord", "{}").success(function (data) {
        $scope.items = JSON.parse(data.d);
        $scope.search();
    });

    var searchMatch = function (haystack, needle) {
        if (!needle) {
            return true;
        }
        return haystack.toString().toLowerCase().indexOf(needle.toLowerCase()) !== -1;
    };
    $scope.leftNextPages = function () {
        $scope.leftStart += 4;
    }
    $scope.RightPriviousPages = function () {
        $scope.rightStart -= 2;
    }

    // init the filtered items
    $scope.search = function () {
        $scope.filteredItems = $filter('filter')($scope.items, function (item) {
            for (var attr in item) {
                if (searchMatch(item[attr], $scope.query))
                    return true;
            }
            return false;
        });
        // take care of the sorting order
        if ($scope.sortingOrder !== '') {
            $scope.filteredItems = $filter('orderBy')($scope.filteredItems, $scope.sortingOrder, $scope.reverse);
        }
        $scope.currentPage = 0;
        // now group by pages
        $scope.groupToPages();
    };

    // calculate page in place
    $scope.groupToPages = function () {
        $scope.pagedItems = [];
        if ($scope.filteredItems) {
            for (var i = 0; i < $scope.filteredItems.length; i++) {
                if (i % $scope.itemsPerPage === 0) {
                    $scope.pagedItems[Math.floor(i / $scope.itemsPerPage)] = [$scope.filteredItems[i]];
                } else {
                    $scope.pagedItems[Math.floor(i / $scope.itemsPerPage)].push($scope.filteredItems[i]);
                }
            }
            $scope.rightStart = $scope.pagedItems.length;
            $scope.leftStart = 0;
        }

    };

    $scope.range = function (start, end) {
        var ret = [];
        if (!end) {
            end = start;
            start = 0;
        }
        for (var i = start; i < end; i++) {
            ret.push(i);
        }
        return ret;
    };

    $scope.prevPage = function () {
        if ($scope.currentPage > 0) {
            $scope.currentPage--;
        }
    };

    $scope.nextPage = function () {
        if ($scope.currentPage < $scope.pagedItems.length - 1) {
            $scope.currentPage++;
        }
    };

    $scope.setPage = function () {
        $scope.currentPage = this.n;
    };

    // functions have been describe process the data for display
    $scope.search();

    // change sorting order
    $scope.sort_by = function (newSortingOrder) {
        if ($scope.sortingOrder == newSortingOrder)
            $scope.reverse = !$scope.reverse;

        $scope.sortingOrder = newSortingOrder;

        // icon setup
        $('th a i').each(function () {
            $(this).removeClass().addClass('icon-sort');
        });
        if ($scope.reverse)
            $('th.' + newSortingOrder + ' i').removeClass().addClass('icon-chevron-up');
        else
            $('th.' + newSortingOrder + ' i').removeClass().addClass('icon-chevron-down');
        //recall function to display sorted Data..
        $scope.search();
    };
}

Create one webservice file named WSTest.asmx like:
using System.Collections.Generic;
using System.Web.Services;
using System.Web.Script.Serialization;

namespace First
{
    /// <summary>
    /// Summary description for WSTest
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    [System.Web.Script.Services.ScriptService]
    public class WSTest : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }

        [WebMethod]
        public string getBulkRecord()
        {
            List<demo> lst = new List<demo>();
            for (int i = 0; i < 10000; i++)
            {
                demo d = new demo();
                d.Email = "test." + i + "@gmail.com";
                d.FirstName = "First Name" + i;
                d.ID = i;
                d.LastName = "Last Name" + i;
                lst.Add(d);
            }
            JavaScriptSerializer js = new JavaScriptSerializer();
            js.MaxJsonLength = 50000000;
            return js.Serialize(lst);
        }

    }
    public class demo
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public int ID { get; set; }
    }
}



Read More

Wednesday, May 13, 2015

submit form without passing any data and get all data of form in webmethod

Leave a Comment
script for submiting form to the specifix url.. write SubmitForm.js as follows:

//to call any web service without passing data and get all form data in web service.. Added By Vimal Vataliya
$.fn.SubmitForm = function (url, callback) {
    var form = $(this);
    if (document.getElementById("test_if")) { }//check if this id is already exist
    else {
        var ifram = document.createElement("iframe");//create iframe to store json result
        ifram.id = "test_if";
        ifram.name = "test_if";
        ifram.height = "0px";
        ifram.width = "0px";
        ifram.onload = function () {
            if (form.attr("action")) {//call success function and then distroy iframe and form action url
                callback(document.getElementById("test_if").contentDocument.body.innerText);
                $("#test_if").remove();
                form.removeAttr("action");
            }
        }
        document.body.appendChild(ifram);
        $("#test_if").css({ position: "absolute", top: -1000, left: -1000 });
    }
    $(this).attr("action", url);
    $(this).attr("target", "test_if");
    $(this).submit();
}


then your aspx page like this:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="jQuery_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="../js/jquery-1.10.2.js" type="text/javascript"></script>
    <script src="SubmitForm.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#btn").click(function () {
                $("#form1").SubmitForm("../WebService.asmx/FillData", test);
            });

        });
        function test(a) {
            var r = $.parseJSON(a);
            alert(r);
        }
    </script>
</head>
<body>
    <form id="form1" enctype="multipart/form-data" method="post">
    <div>
        <input type="text" id="txt" name="txt" /><br />
        <input type="text" id="Text1" name="txt1" /><br />
        <input type="text" id="Text2" name="txt2" /><br />
        <input type="file" id="fu" name="fu" /><br />
        <input type="button" id="btn" value="Submit" />
    </div>
    </form>
</body>
</html>

your WebService.asmx file like this:

using System;
using System.Web;
using System.Web.Services;

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{

    public WebService()
    {

        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

 
    [WebMethod]
    public string HelloWorld()
    {
        return "Hello World";
    }
    [WebMethod]
    public void FillData()
    {
        HttpPostedFile hp = (HttpPostedFile)HttpContext.Current.Request.Files["fu"];
        string a = Convert.ToString(HttpContext.Current.Request.Form["txt"]);
        string b = Convert.ToString(HttpContext.Current.Request.Form["txt1"]);
        string c = Convert.ToString(HttpContext.Current.Request.Form["txt2"]);
        HttpContext.Current.Response.Write(a + "_" + b + "_" + c);
    }

  

}






Read More