Tuesday, December 7, 2010

Gridview check all and post form data with jquery

I am going to show an example of doing some cool stuff using jquery and VS2010.
I need these 2 files:
jquery
http://www.json.org/json2.js

<%@ Page Language="C#" AutoEventWireup="true" 
CodeFile="test.aspx.cs" Inherits="jquerytest_test" %>
 
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="jquery-1.4.4.min.js" type="text/javascript"></script>
    <script src="json2.js" type="text/javascript"></script>
    <script type="text/javascript">
 
    //-------------------------------------------------------------------------
        $(document).ready(function () {
            var gridId = '#<%=grid.ClientID%>';
 
            ConfigureAllCheckBox(gridId);
 
            $(gridId + " input[id*='chkThis']:checkbox").click(function () {
                UpdateFooter(gridId);
                ConfigureAllCheckBox(gridId);
            });
 
            $(gridId + " input[id*='chkAll']:checkbox").click(function () {
                if ($(this).is(':checked')) 
                    $(gridId + " input[id*='chkThis']:checkbox").attr('checked', true);
                else 
                    $(gridId + " input[id*='chkThis']:checkbox").attr('checked', false);
 
                UpdateFooter(gridId);
            });
 
        });
 
        function ConfigureAllCheckBox(gridId) {
            var totalCheckboxes = $(gridId + " input[id*='chkThis']:checkbox").length;
            var checkedCheckboxes = $(gridId + " input[id*='chkThis']:checkbox:checked").length;
 
            if (totalCheckboxes == checkedCheckboxes)
                $(gridId + " input[id*='chkAll']:checkbox").attr('checked', true);
            else
                $(gridId + " input[id*='chkAll']:checkbox").attr('checked', false);
            
        }
 
        function UpdateFooter(gridId) {
 
            var totalId = 'txtTotalAmount';
 
            var total = 0;
 
            $(gridId + " input[id*='chkThis']:checkbox:checked").each(function () {
                total = total + parseFloat($(this).val());
            });
            $(gridId + " input[id*=" + totalId + "]").val(total);
        }
        //-------------------------------------------------------------
        $(document).ready(function () {
            $("#btnSubmit1").click(sendData1);
            $("#btnSubmit2").click(sendData2);
        });
 
        function sendData1() {
 
            $("#divResult").html("Please wait...");
 
            var arForm = $("#form1").serializeArray();
 
            $.ajax({ url: "test.aspx/SendData1",
                type: "POST",
                contentType: "application/json",
                data: JSON.stringify({ formVars: arForm }),
                dataType: "json",
                success: function (result) {
                    $("#divResult").html(result.d);
                },
                error: function (xhr, status) {
                    alert("An error occurred: " + status);
                }
            });
        }
        function sendData2() {
 
            $("#divResult").html("Please wait...");
 
            var x = JSON.stringify({ name: "sam", city: "sydney", date: new Date() });
 
 
            $.ajax({ url: "test.aspx/SendData2",
                type: "POST",
                contentType: "application/json",
                data: x,
                dataType: "json",
                success: function (result) {
                    $("#divResult").html(result.d);
                },
                error: function (xhr, status) {
                    alert("An error occurred: " + status);
                }
            });
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
           <asp:GridView ID="grid" runat="server" AutoGenerateColumns="false" ShowHeader="true" ShowFooter="true">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <span id="lblID" runat="server"><%# Eval("ID") %></span>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <span id="lblName" runat="server"><%# Eval("Name") %></span>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <span id="lblAmount" runat="server"><%# Eval("Amount") %></span>
                    </ItemTemplate>
                    <FooterTemplate>
                        <input type="text" id="txtTotalAmount"
 value="$0.00" style="border:solid 1px Black;width:100px;background-color:#D1D1D1" onfocus="this.blur();" /> 
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <HeaderTemplate>
                        All<input type="checkbox" runat="server" id="chkAll" />
                    </HeaderTemplate>
                    <ItemTemplate>
                        <input type="checkbox" runat="server" id="chkThis" value='<%# Eval("Amount") %>' />
                    </ItemTemplate>
                </asp:TemplateField> 
            </Columns>
        </asp:GridView>
 
           <input type="button" id="btnSubmit1" value="post form vars" />&nbsp;
           <input type="button" id="btnSubmit2" value="post data" />
           <div id="divResult" ></div>
    </div>
    </form>
</body>
</html>

-----------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
 
public partial class jquerytest_test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            List<MyEntity> list = new List<MyEntity>();
            list.Add(new MyEntity() { ID = 1, Name = "toyota", Amount = 4200 });
            list.Add(new MyEntity() { ID = 2, Name = "mazda", Amount = 5200 });
            list.Add(new MyEntity() { ID = 3, Name = "honda", Amount = 3000 });
            list.Add(new MyEntity() { ID = 4, Name = "bmw", Amount = 1200 });
            grid.DataSource = list;
            grid.DataBind();
        }
    }
 
    [System.Web.Services.WebMethod()] 
    public static string SendData1(NameValue[] formVars)
    {
        string result = "Your form variables:<br/>";                        
        foreach (NameValue nv in formVars)
        {
            //ignore _ViewState/_EventValidation
            if (!nv.Name.StartsWith("__"))
            {
                result = result + nv.Name 
+ " : " + HttpUtility.HtmlEncode(nv.Value) + "<br/>";
            }
        }
        return result;
    }
 
    [System.Web.Services.WebMethod()]
    public static string SendData2(string name, string city, DateTime date)
    {
        return "you entered:<br/> " + name + " in " + city + " in " + date.ToString();
    }
}
 
public class MyEntity
{
    public int ID { get; set; }
    public string Name { get; set; }
    public decimal Amount { get; set; }
}
 
public class NameValue
{
    public string Name { get; set; }
    public string Value { get; set; }
}

2 comments:

mahakk01 said...

The example given in this post is not very easy buy interesting one. The code is bit difficult for the beginners but I have to say that jquery method is very well used in this example. Maintain your creativity. Thanks.
digital signature

Dhruv Patel said...

This is perfect example I was searching for, after lot of googling I found this.

other example only help on .aspx side but above also help in server side.

Thanks a lot.

Post a Comment