Showing posts with label Jquery. Show all posts
Showing posts with label Jquery. Show all posts

Thursday, August 1, 2013

How to post array of hashes in wcf

In this post I will show you how to post json array hashes in wcf rest service.Before going to code snippet let's discuss some basic terminology.

What is Array of Hashes
Array of hashes is a data structure in which each record itself contains key/value pairs. Arrays of hashes are used less frequently than the other structures.Below is example of array of hashes
AoH = (
    {
       husband  => "barney",
       wife     => "betty",
       son      => "bamm bamm",
    },
    {
       husband => "george",
       wife    => "jane",
       son     => "elroy",
    },

    {
       husband => "homer",
       wife    => "marge",
       son     => "bart",
    },
  );
JSON String

When we enclosed the json data into quote then we called this string is JSON string
var jsonString='[{ "x": 10, "y": 20, "z": 30 }, { "x": 12, "y": 21, "z": 33 }, { "x": 13, "y": 23, "z": 35}]';

Object literal
When we don't enclosed string in quote then we called this as JSON object literals
var jsonObject= [{ "x": 10, "y": 20, "z": 30 }, { "x": 12, "y": 21, "z": 33 }, { "x": 13, "y": 23, "z": 35}];

For this demo I am going to use JSON.NET library.First go to nuget package manager and install json lib.After that create a simple REST service shown as below.
https://images-blogger-opensocial.googleusercontent.com/gadgets/proxy?url=http://3.bp.blogspot.com/-pxgGPGCnpAE/UfqRQKBLOMI/AAAAAAAACis/VwfcmWb2BWc/s640/newton.png&container=blogger&gadget=a&rewriteMime=image/*

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using Newtonsoft.Json;
namespace WcfService2
{

    public class Service1 : IService1
    {
        public string GetData(string value)
        {
            StringBuilder stringBuilder = new StringBuilder();
            dynamic data = JsonConvert.DeserializeObject(value);
            foreach (var item in data)
            {
                stringBuilder.Append(item.x);
            }
            return stringBuilder.ToString();
        }

    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WcfService2
{

    [ServiceContract]
    public interface IService1
    {

        [OperationContract]
        [WebInvoke(Method = "POST")]
        string GetData(string value);

    }

}

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WcfService2.WebForm1" %>

<!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="Scripts/jquery-2.0.2.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#id").click(function () {
                var d = '[{ "x": 10, "y": 20, "z": 30 }, { "x": 12, "y": 21, "z": 33 }, { "x": 13, "y": 23, "z": 35}]';
                $.ajax({
                    type: 'POST',
                    url: "http://localhost:1449/Service1.svc/GetData",
                    data: JSON.stringify(d),
                    contentType: "application/json",
                    success: function (data) {
                    },
                    complete: function () {
                    }
                });
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input type="button" value="S" id="id" />
    </div>
    </form>
</body>
</html>

Friday, February 24, 2012

Calling cross domain wcf service using Jquery

In this post,I will show you how to call cross domain service using jquery.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.IO;
using System.ServiceModel.Web;
using System.Runtime.Serialization.Json;

namespace CorssDomainService
{
    [DataContract]
    public class Order
    {
        [DataMember]
        public int ID { get; set; }
        [DataMember]
        public DateTime OrderDate { get; set; }
        [DataMember]
        public string Name { get; set; }

    }
    [ServiceContract]
    public interface IOrderService
    {
        [OperationContract]
        [WebInvoke(Method = "GET", UriTemplate = "/",
           ResponseFormat = WebMessageFormat.Json
   )]
        string ProcessOrder();

    }
    [ServiceBehavior]
    public class OrderService : IOrderService
    {
        [OperationBehavior]
        public string ProcessOrder()
        {
            Order order = new Order
            {
                ID = 1,
                OrderDate = DateTime.Now,
                Name = "Laptop"

            };

            DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(Order));
            MemoryStream stream = new MemoryStream();
            json.WriteObject(stream, order);
            return Encoding.UTF8.GetString(stream.ToArray());

        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            ServiceHost host = new ServiceHost(typeof(OrderService));
            host.Open();
            Console.WriteLine("Service is ready");
            Console.ReadLine();
        }
    }
}
<?xml version="1.0"?>
<configuration>
  <system.serviceModel>
    <services>
      <service name="CorssDomainService.OrderService" behaviorConfiguration="serviceBehave">
        <endpoint address="rest" bindingConfiguration="crossDomain"  behaviorConfiguration="enableScriptBehaviour"
                  binding="webHttpBinding"
                  contract="CorssDomainService.IOrderService"></endpoint>
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:9090/"/>
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="serviceBehave">
          <serviceMetadata httpGetEnabled="true" httpGetUrl="mex"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="enableScriptBehaviour">
          <webHttp></webHttp>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <bindings>
      <webHttpBinding>
        <binding name="crossDomain" crossDomainScriptAccessEnabled="true"></binding>
      </webHttpBinding>
    </bindings>
  </system.serviceModel>
</configuration>
Now,create a website in visual studio,and paste following code into it
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_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 type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $.getJSON("http://localhost:9090/Rest?callback=?", null, function (data) {
                alert(data);
            });

        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>

Thursday, October 20, 2011

How to validate asp.net form using Jquery

In this post I will show you how to validate asp.net form using jqery. Create a new website,add a new js file ,and add following code inside it
function validateForm(e) {
    var formIsValid = true;
    // check that a valid email address has been entered
    var emailRegExp = /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/;
    if (!emailRegExp.test(String($("#txtEmail").val()).toUpperCase())) {
        addError("txtEmail", "Please enter a valid email address.");
        formIsValid = false;
    } else {
        removeError("txtEmail");
    }

    // check that first name has one or more characters
    if ($("#txtFirstName").val() == '') {
        addError("txtFirstName", "This field is required.");
        formIsValid = false;
    } else {
        removeError("txtFirstName");
    }
    // check that last name has one or more characters
    if ($("#txtLastName").val() == '') {
        addError("txtLastName", "This field is required.");
        formIsValid = false;
    } else {
        removeError("txtLastName");
    }

    // check that a valid phone number is entered
    var phoneRegExp = /^\(?[1-9]\d{2}\)?\s?\-?\.?\d{3}\s?\-?\.?\d{4}$/;
    if (!phoneRegExp.test($("#txtPhone").val())) {
        addError("txtPhone", "Valid phone number required.");
        formIsValid = false;
    } else {
        removeError("txtPhone");
    }

    if (!formIsValid) {
        e.preventDefault();
    }
}

function addError(id, msg) {
    if ($("#" + id).parent().find("label[class=error]").attr("generated") == "true") {
        $("#" + id).parent().find("label[class=error]").css("display", "block");
    } else {
        $("#" + id).parent().append('<label for="' + id + '" generated="true" class="error">' + msg + '</label>').css("display", "block");
    }
}
function removeError(id) {
    $("#" + id).parent().find("label[class=error]").css("display", "none");
}
Add a new page.Then add reference of jquery and above js file
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!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">
    <script type="text/javascript" src="Scripts/jquery-1.4.1.js"></script>
    <script type="text/javascript" src="Scripts/Validation.js"></script>
    <title></title>
    <script type="text/javascript">
        $(document).ready(function () {
            $(".submitForm").click(function (e) {
                validateForm(e);
            });
        });
    </script>
    <style type="text/css">
    .error{color:Red;}
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <table class="style1">
        <tr>
            <td>
                FirstName
            </td>
            <td>
                <asp:TextBox ID="txtFirstName"  runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>
                LastName
            </td>
            <td>
                <asp:TextBox ID="txtLastName"  runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>
                Phone Number
            </td>
            <td>
                <asp:TextBox ID="txtPhone"  runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>
                Email
            </td>
            <td>
                <asp:TextBox ID="txtEmail"  runat="server"></asp:TextBox>
            </td>
        </tr>
    </table>
    <div>
        <input type="button" id="btnSubmit" class="submitForm" value="Submit" />
    </div>
    </form>
</body>
</html>

Saturday, October 1, 2011

How to sum the value of gridview column using jquery

In this post I will show how to sum the value of gridview column on selection of checkbox .Let us suppose that you have a gridview which has three column named Name,Quantity and Price.Now your requirement is to sum the value of price filed on selection of checkbox.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!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">
    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <title></title>
    <script type="text/javascript">
        $(document).ready(function () {
    var total;
    //Column index value of price field (Column index start from 1)
    var columnIndexValue = 4;
    var checked = $('input:checkbox').click(function (e) {
    var total = 0.0;
                $("tr:has(:checkbox:checked) td:nth-child(" + columnIndexValue + ")").each(function () {
                    total += parseFloat($(this).text());
                });
                $('#Sum').text("your total is:" + total.toFixed(2));
            });
        });
        
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:GridView ID="grdItems" runat="server" AutoGenerateColumns="false">
    <Columns>
    <asp:TemplateField>
    <ItemTemplate>
    <asp:CheckBox ID="chkItem" runat="server" />
    </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Name">
    <ItemTemplate>
    <asp:Label ID="label2" Text='<%#Eval("Name") %>' runat="server" />
    </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Quantity">
    <ItemTemplate>
    <asp:Label ID="Label1" Text='<%#Eval("Quantity") %>' runat="server" />
    </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Price">
    <ItemTemplate>
    <asp:Label ID="Label2" Text='<%#Eval("Price") %>' runat="server" />
    </ItemTemplate>
    </asp:TemplateField>
    </Columns>
    </asp:GridView>
    </div>
    <div id="Sum">
    </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;
public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        grdItems.DataSource = new Item().Items;
        grdItems.DataBind();
    }
}
public class Item
{
    public string Name { get; set; }
    public int Quantity { get; set; }
    public decimal Price { get; set; }
    public List<Item> Items
    {
        get
        {
    return new List<Item>()
                       {
    new Item(){Name = "Item01",Quantity = 10,Price = 180M},
    new Item(){Name = "Item01",Quantity = 11,Price = 184M},
    new Item(){Name = "Item01",Quantity = 12,Price = 190M},
    new Item(){Name = "Item01",Quantity = 13,Price = 110M},
                       };
        }
    }
}

Click here for live Demo

Monday, June 27, 2011

How to display progress indicator during ajax call in asp.net[Jquery]

aspdotnetcodebook In this post I will show you how to display progress indicator during ajax call.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Jquery_Progress.aspx.cs"
    Inherits="Jquery_Progress" %>

<!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="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <style type="text/css">
        .loader
        {
            display: none;
            background-color: Red;
            width: 100px;
        }
    </style>
    <script language="javascript" type="text/javascript">
        $(document).ready(function () {
            $("#btnLoad").click(function (e) {
                e.preventDefault();
                $("#gvData").html("");
                $("#loader").show();
                sendData();
            });
        });
        function sendData() {
            var loc = window.location.href;
            loc = (loc.substr(loc.length - 1, 1) == "/") ? loc + "Jquery_Progress.aspx" : loc;
            $.ajax({
                type: "POST",
                url: loc + "/GetAllProducts",
                contentType: "application/json;charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    $("#loader").hide();
                    $("#gvData").html(msg.d);
                },
                error: function () {
                    alert("An unexpected error has occurred during processing.");
                }
            });
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:Button ID="btnLoad" runat="server" Text="LoadProduct" /><br />
    <div id="gvData">
    </div>
    <div id="loader" class="loader">
        Loading....</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;
using System.Web.Script.Services;
using System.Web.Script.Serialization;
using System.Text;

public partial class Jquery_Progress : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    [WebMethod]
    [ScriptMethod]
    public static string GetAllProducts()
    {
        //Comment below line for production server
        System.Threading.Thread.Sleep(3000);
        StringBuilder sb=new StringBuilder();
        JavaScriptSerializer json=new JavaScriptSerializer();
        List<Product> products = ProductDAL.GetProducts();
        json.Serialize(products, sb);
       return sb.ToString();
    }
}
public class Product
{
    public int ProductID { get; set; }
    public string ProductName { get; set; }
    public string Description { get; set; }
}
public class ProductDAL
{
    public static List<Product> GetProducts()
    {
        return new List<Product>()
                   {
                       new Product() {ProductID = 1, ProductName = "P001", Description = "Desc01"},
                       new Product() {ProductID = 2, ProductName = "P002", Description = "Desc02"},
                       new Product() {ProductID = 3, ProductName = "P003", Description = "Desc03"},
                       new Product() {ProductID = 4, ProductName = "P004", Description = "Desc04"},
                       new Product() {ProductID = 5, ProductName = "P005", Description = "Desc05"},
                   };
    }
}

Highlighting rows/cells of a GridView on hover

aspdotnetcodebook In this post I will show you how to highlight grid view row on mouseover using jquery.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridviewRowColorChange.aspx.cs"
    Inherits="GridviewRowColorChange" %>

<!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="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <style type="text/css">
        .highlight
        {
            background-color:#9999FF;
        }  
        td
        {
            cursor: pointer;
        }
    </style>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#<%=gvProducts.ClientID %> tr").mouseover(function () {
                $(this).addClass("highlight");
            });
            $("#<%=gvProducts.ClientID %> tr").mouseout(function () {
                $(this).removeClass("highlight");
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="gvProducts" runat="server">
        </asp:GridView>
    </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;

public partial class GridviewRowColorChange : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
            gvProducts.DataSource = ProductDAL.GetProducts();
            gvProducts.DataBind();
        }
    }
}
public class Product
{
    public int ProductID { get; set; }
    public string ProductName { get; set; }
    public string Description { get; set; }
}
public class ProductDAL
{
    public static List<Product> GetProducts()
    {
        return new List<Product>()
                   {
                       new Product() {ProductID = 1, ProductName = "P001", Description = "Desc01"},
                       new Product() {ProductID = 2, ProductName = "P002", Description = "Desc02"},
                       new Product() {ProductID = 3, ProductName = "P003", Description = "Desc03"},
                       new Product() {ProductID = 4, ProductName = "P004", Description = "Desc04"},
                       new Product() {ProductID = 5, ProductName = "P005", Description = "Desc05"},
                   };
    }

}

How to select/deselect all checkbox in gridview using jquery

aspdotnetcodebook In this post I will show how to select/deselect checkbox present inside gridview using jquery.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridViewSelectAll.aspx.cs"
    Inherits="GridViewSelectAll" %>

<!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="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#<%=gvProducts.ClientID%> input[id$='chkAll']:checkbox").click(function () {
                $("#<%=gvProducts.ClientID%> input[id*='chkSelected']:checkbox").attr('checked', $(this).is(':checked'));
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView runat="server" ID="gvProducts" AutoGenerateColumns="false">
            <Columns>
                <asp:TemplateField>
                    <HeaderTemplate>
                        <input type="checkbox" id="chkAll" runat="server" value='<%#Eval("ProductID") %>' />
                    </HeaderTemplate>
                    <ItemTemplate>
                        <input type="checkbox" id="chkSelected" runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="ProductName" HeaderText="ProductName" />
                <asp:BoundField DataField="Description" HeaderText="Description" />
            </Columns>
        </asp:GridView>
    </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;

public partial class GridViewSelectAll : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        gvProducts.DataSource = ProductDAL.GetProducts();
        gvProducts.DataBind();
    }
}
public class Product
{
    public int ProductID { get; set; }
    public string ProductName { get; set; }
    public string Description { get; set; }
}
public class ProductDAL
{
    public static List<Product> GetProducts()
    {
        return new List<Product>()
                   {
                       new Product() {ProductID = 1, ProductName = "P001", Description = "Desc01"},
                       new Product() {ProductID = 2, ProductName = "P002", Description = "Desc02"},
                       new Product() {ProductID = 3, ProductName = "P003", Description = "Desc03"},
                       new Product() {ProductID = 4, ProductName = "P004", Description = "Desc04"},
                       new Product() {ProductID = 5, ProductName = "P005", Description = "Desc05"},
                   };
    }

}

Sunday, June 26, 2011

How to enlarge image on mouseover in asp.net using jquery

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

<!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 type="text/javascript" src="Scripts/jquery-1.4.1.js"></script>
    <style type="text/css">
        .thumbnail
        {
            height: 100px;
            width: 100px;
            position: relative;
        }
        .image
        {
            position: relative;
            width: 400px;
            height: 250px;
        }
    </style>
    <script language="javascript" type="text/javascript">
        $(document).ready(function () {
            $(".thumbnail").mouseover(function () {
                $(".thumbnail").css("opacity", ".5");
                $(this).animate({ opacity: 1.0 });
                $("#imgContainer").append("<img class='image' src='" + $(this).attr("src") + "' />");

            });
            $(".thumbnail").mouseout(function () {
                $(".thumbnail").css("opacity", "1.0");
                $(".image").remove();
            });
        });
       
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    </div>
    </form>
    <div align="center">
        <img alt="" class="thumbnail" src="Images/Tree.jpg" />
        <img class="thumbnail" src="Images/dock.jpg" alt="" />
        <img class="thumbnail" src="Images/forest.jpg" alt="" />
        <img class="thumbnail" src="Images/garden.jpg" alt="" />
        <div id="imgContainer">
        </div>
    </div>
</body>
</html>

Wednesday, June 22, 2011

How to Implement jQuery UI slider with ASP.NET

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

<!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">
    <link type="text/css" rel="Stylesheet" href="http://ajax.microsoft.com/ajax/jquery.ui/1.8.5/themes/start/jquery-ui.css" />
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
    </script>
    <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.ui/1.8.5/jquery-ui.min.js">
    </script>
    <title></title>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#slider").slider(
            {
                min: <%=MinValue%>,
                max: <%=MaxValue%>,
                step: <%=Step %>,
                slide: function (event, ui) {
                    $("#txtValue").val(ui.value);
                }
            });
        });
    
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <div id="slider" style="width: 200px;">
        </div>
        <br />
        <asp:TextBox ID="txtValue" runat="server"></asp:TextBox>
    </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;

public partial class Slider_Demo : System.Web.UI.Page
{
    public const int MinValue = 0;
    public const int MaxValue = 100;
    public const int Step = 5;
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

Tuesday, December 7, 2010

Jquery and CheckboxList

In this post i am going to show you how use jquery in asp.net to select the checkbox of Checkbox List
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="RadioButtonListJquery.aspx.cs"
    Inherits="RadioButtonListJquery" %>

<!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="Scripts/jquery-1.3.2.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#selectAll").click(function () {
                $("input[type='checkbox'").not("#selectAll").each(function () {
                    $(this).attr("checked", "true");

                });
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <input type="button" value="Select All" id="selectAll" />
    <div id="divLanguage">
        <asp:CheckBoxList ID="chkList" runat="server">
            <asp:ListItem Text="C#" Value="1"></asp:ListItem>
            <asp:ListItem Text="Java" Value="1"></asp:ListItem>
            <asp:ListItem Text="C++" Value="1"></asp:ListItem>
            <asp:ListItem Text="C" Value="1"></asp:ListItem>
        </asp:CheckBoxList>
    </div>
    </form>
</body>
</html>

Sunday, June 20, 2010

jQuery Autocomplete and ASP.NET

In this post i am going to show how to use jquery Autocomplte plugin in asp.net.


aspdotnetcodebook
  • Open Microsoft Visual Studio .NET. In Visual C# .NET, create a new WebSite
  • Right click on new website and add a new class(DummyDAL.cs) in App_Code folder and copy the following code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

public class Country
{
    public int ID { get; set; }
    public string CountryName { get; set; }


    public System.Collections.Generic.List<Country> GetList()
    {
        System.Collections.Generic.List<Country> list = new System.Collections.Generic.List<Country>()
        {
            new Country(){ID=1,CountryName="Inida"},
            new Country(){ID=1,CountryName="Indonesia"},
            new Country(){ID=2,CountryName="USA"},
            new Country(){ID=3,CountryName="UK"},
            new Country(){ID=4,CountryName="Australia"},
            new Country(){ID=5,CountryName="Newzeland"}

        };
        return list;
    }
}





  •  Right click on website and add new Generic Handler named AutoComplete.ashx and add following code
     
    <%@ WebHandler Language="C#" Class="AutoComplte" %>
    
    using System;
    using System.Web;
    using System.Linq;
    using System.Linq.Expressions;
    
    public class AutoComplete : IHttpHandler
    {
    
        public void ProcessRequest(HttpContext context)
        {
            string param = HttpContext.Current.Request.Params["q"];
            Country objCountry = new Country();
            var query = from p in objCountry.GetList()
                        where p.CountryName.ToLower().StartsWith(param.ToLower())
                        select p;
            foreach (var item in query)
            {
                context.Response.Write(item.CountryName + Environment.NewLine);
    
            }
        }
    
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    
    } 
     
    In this last add following code in Default.aspx(in my case autocomplete.aspx)
    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="AutoComplete.aspx.cs" Inherits="AutoComplete" %>
    
    <!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="Scripts/jquery-1.3.2.js" type="text/javascript"></script>
    
        <script src="Scripts/jquery-autocomplete.js" type="text/javascript"></script>
    
        <style type="text/css">
            .ac_results
            {
                padding: 0px;
                border: 1px solid WindowFrame;
                background-color: Window;
                overflow: hidden;
            }
            .ac_results ul
            {
                width: 100%;
                list-style-position: outside;
                list-style: none;
                padding: 0;
                margin: 0;
            }
            .ac_results iframe
            {
                display: none; /*sorry for IE5*/
                display: /**/ block; /*sorry for IE5*/
                position: absolute;
                top: 0;
                left: 0;
                z-index: -1;
                filter: mask();
                width: 3000px;
                height: 3000px;
            }
            .ac_results li
            {
                margin: 0px;
                padding: 2px 5px;
                cursor: pointer;
                display: block;
                width: 100%;
                font: menu;
                font-size: 12px;
                overflow: hidden;
            }
            .ac_loading
            {
                background: Window url('./indicator.gif') right center no-repeat;
            }
            .ac_over
            {
                background-color: Highlight;
                color: HighlightText;
            }
        </style>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <h3>
                Country</h3>
            <input type="text" id="country" name="country" />
    
            <script>
                $("#country").autocomplete("AutoComplete.ashx");
            </script>
    
        </div>
        </form>
    </body>
    </html>
     
     
     
     
     
    Click here for {{Demo}}

Monday, February 15, 2010

Autocomplete using Jquery

aspdotnetcodebook
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_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">

    <script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>

    <title></title>
    <style type="text/css">
        .listbox
        {
            position: relative;
            left: 10px;
            margin: 10px;
            width: 200px;
            background-color: #000;
            color: #fff;
            border: 2px solid #000;
        }
        .nameslist
        {
            margin: 0px;
            padding: 0px;
            list-style: none;
        }
        .hover
        {
            background-color: Teal;
            color: blue;
        }
    </style>

    <script type="text/javascript">
        $(document).ready(function() {
            $('.listbox').hide();
            $('#country').keyup(function() {
                var country = $('#country').val();
                $.ajax({
                    type: "POST",
                    url: "Default.aspx/User",
                    data: "{'country': '" + country + "'}",
                    dataType: "json",
                    contentType: "application/json",
                    success: function(html) {
                        $('.listbox').show();
                        $('.nameslist').html(html.d);
                        $('li').hover(function() {
                            $(this).addClass('hover');
                        }, function() {
                            $(this).removeClass('hover');
                        });
                        $('li').click(function() {
                            $('#country').val($(this).text());
                            $('.listbox').hide();
                        });
                    }
                });
                return false;
            });
        });
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <span class="label">Enter Country Name</span>
    <input type="text" name="country" id="country" />
    <div class="listbox">
        <div class="nameslist">
        </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.Text;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    [System.Web.Services.WebMethod]
    public static string User(string country)
    {

        Country objCountry = new Country();
        var query = from p in objCountry.GetList()
                    where p.CountryName.ToLower().StartsWith(country.ToLower())
                    select p;
        StringBuilder sb = new StringBuilder();
        foreach (var item in query)
        {
            sb.Append("<li>" + item.CountryName + "</li>");

        }
        return sb.ToString();
    }

}

public class Country
{
    public int ID { get; set; }
    public string CountryName { get; set; }


    public List<Country> GetList()
    {
        List<Country> list = new List<Country>()
        {
            new Country(){ID=1,CountryName="Inida"},
            new Country(){ID=2,CountryName="USA"},
            new Country(){ID=3,CountryName="UK"},
            new Country(){ID=4,CountryName="Australia"},
            new Country(){ID=5,CountryName="Newzeland"}

        };
        return list;
    }
}

Monday, January 4, 2010

GridView row double click and postback using Jquery

Photobucket
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_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">
    <style type="text/css">
        .selected
        {
            background-color: Red;
        }
    </style>

    <script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>

    <title></title>

    <script type="text/javascript">
    var selected = null;

$(document).ready(function(){
   $("#<%=GridView1.ClientID %>").find("tr").click(function(){
      $(selected).removeClass("selected");
      $(this).addClass("selected");
      selected = this;
   });
   $("#<%=GridView1.ClientID %>").find("tr").dblclick(function(){

      /* if you just want to dig into that record I would put a custom attribute on the row */
      window.location = "<%=ResolveUrl("~/Default2.aspx")%>?record=" + $(this).find("td:last").text();
      /* or you could have a hidden LinkButton in the row (Text="" or not set) that you could trigger. Make sure you set the CommandName="Something" and CommandArgument="RecordId" */
      $(this).find("a").click();
   });

});


    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
    </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;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //Create Object of person class
        Person personObject = new Person();
        //Assign Person list to GridView
        GridView1.DataSource = personObject.GetPersonList();
        //Call Bindmethod of GridView
        GridView1.DataBind();

    }
}
public class Person
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public List<Person> GetPersonList()
    {
        //Retrun List of Person
        List<Person> list = new List<Person>()
        {
            new Person{ID=1,Name="Person1",Age=32},
            new Person{ID=2,Name="Person2",Age=45},
            new Person{ID=3,Name="Person3",Age=43},
            new Person{ID=4,Name="Person4",Age=21},
            new Person{ID=5,Name="Person5",Age=76},
            new Person{ID=6,Name="Person6",Age=54},

        };

        return list;

    }
}

Sunday, January 3, 2010

How to get cell value of gridview using JQUERY

Photobucket
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_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="Scripts/jquery-1.3.2.js" type="text/javascript"></script>

    <script type="text/javascript">
        $(document).ready(function() {
            var list = "";
            $("#btnGet").click(function() {
                $("#<%=GridView1.ClientID %> tr").each(function() {
                    //Skip first(header) row
                    if (!this.rowIndex) return;
                    var age = $(this).find("td:last").html();
                    list += age + "</br>";

                });
                $("#listAge").html(list)
            });

        });
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
    </div>
    <asp:GridView ID="GridView1" runat="server">
    </asp:GridView>
    <input type="button" id="btnGet" value="Get Cell Value" />
    <div id="listAge">
    </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;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
       //Create Object of person class
        Person personObject = new Person();
        //Assign Person list to GridView
        GridView1.DataSource = personObject.GetPersonList();
        //Call Bindmethod of GridView
        GridView1.DataBind();

    }
}
public class Person
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public List<Person> GetPersonList()
    {
        //Retrun List of Person
        List<Person> list = new List<Person>()
        {
            new Person{ID=1,Name="Person1",Age=32},
            new Person{ID=2,Name="Person2",Age=45},
            new Person{ID=3,Name="Person3",Age=43},
            new Person{ID=4,Name="Person4",Age=21},
            new Person{ID=5,Name="Person5",Age=76},
            new Person{ID=6,Name="Person6",Age=54},

        };

        return list;

    }

}