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

How To change the color of gridview row on mouseover using JQUERY

Photobucket
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.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 id="Head1" runat="server">
    <title></title>

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

    <script type="text/javascript">
        $(document).ready(function() {
            $("#<%=GridView1.ClientID%> tr").filter(function() {
                return $('td', this).length
                && !('table', this).length
            }).hover
                (
                function() { $(this).css("background-color", "red") },
                function() { $(this).css("background-color", "white") }
                );
        });

    </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;

    }

}

How To Create TextBox Dynamically using Jquery t and Read Control Value In Code Behind

<%@ 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() {
            $("#btnOfficial").click(function() {
                var hdValue = $("#theValue");
                var num = ($("#theValue").val() - 1) + 2;
                hdValue.val(num);
                var newDiv = $(document.createElement('div')).attr("id", 'my' + num + 'Div');
                newDiv.after().html('<input type="text"  name="TextBox' + num + '" value="TextBox' + num + '" >');
                newDiv.appendTo("#Div1");

            });
        });
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div id="Div1">
    </div>
    <asp:GridView ID="GridView1" runat="server">
    </asp:GridView>
    <input type="button" id="btnOfficial" value="Add Another TextBox" />
    <input type="hidden" value="1" id="theValue" runat="server" />
    <asp:Button ID="btnSave" runat="server" Text="Read" OnClick="btnSave_Click" />
    </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.Collections;

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


    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        List<string> alForm = new List<string>();
        //Textbox id is started
        // with 2 like(TextBox2,TextBox3.....
        for (int i = 2; i < Request.Form.Count - 2; i++)
        {
            string strId = "TextBox" + i.ToString();
            string strValue = Request.Form[strId].ToString();
            alForm.Add(strValue);
            strValue = "";


        }
        //Uncomment this line and test.
        //foreach (string x in Request.Form)
        //{

        //   string strValue = Request.Form[x].ToString();
        //  alForm.Add(strValue);

        //}
        GridView1.DataSource = alForm;
        GridView1.DataBind();
    }
}

How To Use Jquery Google Chart In asp.net

In this post i will show how to add Jquery Google Chart in asp.net. Click Here to download Jquery Google Chart Plugin
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Chart.aspx.cs" Inherits="Chart" %>

<!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>jQuery Google Chart Demo</title>

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

    <script src="jgcharts.pack.js" type="text/javascript"></script>

    <link href="Style/style.css" rel="stylesheet" type="text/css" />

    <script type="text/javascript">
        $(document).ready(function() {
            $("#btnCreate").click(function() {
                $("#bar_chart").html("");
                var api = new jGCharts.Api();
                var opt =
            {
                data: eval($("[id$='hdValue']").val()),
                axis_labels: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'],
                legend: ['X', 'Y'],
                size: '600x335',
                type: $("[id$='ddlType']").val(),
                bg: $("[id$='ddlColor']").val(),
                bar_width: 15
            };
                jQuery('<img>').attr('src', api.make(opt)).appendTo("#bar_chart");
            });
        });
    </script>

    <style type="text/css">
        .style1
        {
            width: 100%;
        }
    </style>
</head>
<body>
    <form id="dform" runat="server">
    <div class="right">
        <h4>
            Demo Chart</h4>
        <div id="bar_chart">
        </div>
        <div id="bar_chart_data">
        </div>
    </div>
    <div class="left">
        <asp:HiddenField ID="hdValue" runat="server" />
        <asp:GridView ID="gvChart" runat="server" AutoGenerateColumns="false">
            <Columns>
                <asp:BoundField DataField="X" HeaderText="X" />
                <asp:BoundField DataField="Y" HeaderText="Y" />
            </Columns>
        </asp:GridView>
    </div>
    <table style="width: 50%; margin-top: 40%;">
        <tr>
            <td>
                Chart Type
            </td>
            <td>
                <asp:DropDownList ID="ddlType" runat="server">
                    <asp:ListItem Value="stripes">Stripes</asp:ListItem>
                    <asp:ListItem Value="p">Pie</asp:ListItem>
                    <asp:ListItem Value="p3">Pie3D</asp:ListItem>
                    <asp:ListItem Value="lc">Line</asp:ListItem>
                    <asp:ListItem Value="bhs">Stacked Bar</asp:ListItem>
                </asp:DropDownList>
            </td>
        </tr>
        <tr>
            <td>
                Background Color
            </td>
            <td>
                <asp:DropDownList ID="ddlColor" runat="server">
                    <asp:ListItem Text="Red" Value="FF0000"></asp:ListItem>
                    <asp:ListItem Text="Light Blue" Value="0000FF"></asp:ListItem>
                    <asp:ListItem Text="Light Purple" Value="FF0080"></asp:ListItem>
                    <asp:ListItem Text="Light Gray" Value="C0C0C0"></asp:ListItem>
                </asp:DropDownList>
            </td>
        </tr>
        <tr>
            <td>
                &nbsp;
            </td>
            <td>
                <input type="button" id="btnCreate" value="Create" />
            </td>
        </tr>
    </table>
    </form>
</body>
</html>
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class Chart : System.Web.UI.Page
{
    private DataTable GetSampleData()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("X");
        dt.Columns.Add("Y");
        dt.Rows.Add("1000", "3003.55");
        dt.Rows.Add("1000", "72.65");
        dt.Rows.Add("1000", "760.89");
        dt.Rows.Add("1000", "354.55");
        dt.Rows.Add("1000", "180.52");
        dt.Rows.Add("1000", "408.54");
        return dt;

    }
    protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dt = GetSampleData();
        gvChart.DataSource = dt;
        gvChart.DataBind();

        ArrayList chartData = new ArrayList();
        foreach (DataRow dr in dt.Rows)
        {
            chartData.Add(String.Format("[{0}, {1}]", dr[0], dr[1].ToString().Replace("-", "")));
        }

        //Convert .NET Array to JS Array
        string ReturnValue = String.Empty;
        for (int i = 0; i < chartData.Count; i++)
        {
            ReturnValue += chartData[i];
            if (i != chartData.Count - 1)
                ReturnValue += ",";
        }

        //Data is returned in the following format: 
        //[[X, Y]

        hdValue.Value = String.Format("[{0}]", ReturnValue);

    }
}
{{download}}

How To Add Jquery Plugin Tablesorter in Gridview

<%@ 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 src="Scripts/Jquery.tablesorter.js" type="text/javascript"></script>

    <script type="text/javascript">
        $(document).ready(function() {
            $("#grdStudent").tablesorter();
        }
        ); 
    
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="grdStudent" runat="server" UseAccessibleHeader="true">
        </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)
    {
        if (!IsPostBack)
        {
            grdStudent.DataSource = new Student().GetAll();
            grdStudent.DataBind();
            MakeAccessible(grdStudent);
        }

    }

    private void MakeAccessible(GridView grid)
    {
        if (grid.Rows.Count > 0)
        {
            //This replaces <td> with <th> and adds the scope attribute
            grid.UseAccessibleHeader = true;

            //This will add the <thead> and <tbody> elements
            grid.HeaderRow.TableSection = TableRowSection.TableHeader;

            //This adds the <tfoot> element. Remove if you don't have a footer row
            grid.FooterRow.TableSection = TableRowSection.TableFooter;
        }
    }
}
public class Student
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
    public List<Student> GetAll()
    {
        List<Student> list = new List<Student>()
        {
            new Student{FirstName="S001",LastName="L01",Age=21},
            new Student{FirstName="S002",LastName="L21",Age=31},
            new Student{FirstName="S003",LastName="L341",Age=51},
            new Student{FirstName="S004",LastName="L021",Age=51},
            new Student{FirstName="S005",LastName="L0231",Age=45},
            new Student{FirstName="S006",LastName="L0231",Age=26},
            new Student{FirstName="S007",LastName="L021",Age=14},
            new Student{FirstName="S008",LastName="L5401",Age=21},
            new Student{FirstName="S009",LastName="L231",Age=21},
            new Student{FirstName="S009",LastName="L0231",Age=21},
            new Student{FirstName="S011",LastName="L0231",Age=21},

        };

        return list;
    }

}
Before using this code read this article How To Make GridView Control Accessible {{Download}}

Cascading Dropdownlist using JQuery and WebService

<%@ 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.2.6.js" type="text/javascript"></script>

  <script type="text/javascript">
      $().ready(function() {
          $.ajax({
              type: "POST",
              url: "WebService.asmx/GetStates",
              data: "{}",
              contentType: "application/json; charset=utf-8",
              dataType: "json",
              success: function(msg) {
                  BindStateddl(msg.d)
              }
          });
          //Fetch related city
          $("#ddlStates").change(function() {
              var StateID = $("#ddlStates > option[@selected]").attr("value");
              $("#ddlCities").html("");
              $.ajax({
                  type: "POST",
                  url: "WebService.asmx/FindCityByID",
                  data: "{ID:'" + StateID + "'}",
                  contentType: "application/json; charset=utf-8",
                  dataType: "json",
                  success: function(msg) {
                      BindCityddl(msg.d)
                  }
              });
          });
      });
      function BindStateddl(msg) {
          $.each(msg, function() {

              $("#ddlStates").append($("<option></option>").val(this['StateId']).html(this['Name']));

          });
      }
      function BindCityddl(msg) {
          $.each(msg, function() {

              $("#ddlCities").append($("<option></option>").val(this['CityID']).html(this['Name']));

          });
      }
  </script>

</head>
<body>
  <form id="form1" runat="server">
  <div>
      <table>
          <tr>
              <td>
                  State
              </td>
              <td>
                  <asp:DropDownList ID="ddlStates" runat="server">
                      <asp:ListItem Value="0">Select</asp:ListItem>
                  </asp:DropDownList>
              </td>
          </tr>
          <tr>
              <td>
                  Cities
              </td>
              <td>
                  <select id="ddlCities" runat="server">
                  </select>
              </td>
          </tr>
      </table>
  </div>
  </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
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
{

  /// <summary>
  /// Filter city by StateID
  /// </summary>
  /// <param name="ID"></param>
  /// <returns></returns>
  [WebMethod]
  public List<Cities> FindCityByID(string ID)
  {
      return GetCities().FindAll(x => x.StateId == int.Parse(ID));

  }
  /// <summary>
  /// Return list of cities.
  /// </summary>
  /// <returns></returns>
  public List<Cities> GetCities()
  {
      List<Cities> cities = new List<Cities>()
          {
              new Cities{CityID=1,StateId=1,Name="Lucknow"},
              new Cities{CityID=2,StateId=1,Name="Allahabad"},
              new Cities{CityID=3,StateId=2,Name="Patiala"},
              new Cities{CityID=4,StateId=2,Name="Amritsar"},
              new Cities{CityID=5,StateId=3,Name="Shimla"},
         
          };
      return cities;
  }


  /// <summary>
  /// Return List of states
  /// </summary>
  /// <returns></returns>
  [WebMethod]
  public List<State> GetStates()
  {

      List<State> states = new List<State>()
          {
              new State{StateId=1,Name="UP"},
              new State{StateId=2,Name="Punjab"},
              new State{StateId=3,Name="Himachal"}
          };
      return states;

  }
  /// <summary>
  /// 
  /// </summary>
  public class State
  {
      public int StateId { get; set; }
      public string Name { get; set; }
  }
  /// <summary>
  /// 
  /// </summary>
  public class Cities
  {
      public int CityID { get; set; }
      public int StateId { get; set; }
      public string Name { get; set; }
  }

}

Download

How to consume WCF service using JQuery

  • Create an ASP.NET Web Application (WCF service)
  • Add a new item, aspx page (Default.aspx)
  • You now have an WCF-service with .svc as extension, and that service implements an Interface. It's in the interface we'll set the attributes needed to return JSON
  • Create a class, Student as below. The attributes "DataContract" and "DataMember" must be defined for the class and the properties that would be returned through the WCF service
[DataContract]
public class Student
{
 [DataMember]
 public int StudentId { get; set; }
 [DataMember]
 public string StudentName { get; set; }
 [DataMember]
 public int Marks1 { get; set; }
 [DataMember]
 public int Marks2 { get; set; }
 [DataMember]
 public string EmailAddress { get; set; }
}
  • Now add a reference to System.ServiceModel.Web this is for WebGet Attribute
  • Add the WebGet-attribute as specified below. The BodyStyle Bare means "Both requests and responses are not wrapped" - we really want nothing more than a true JSON-response. The ResponseFormat should of course be "Json".
[ServiceContract]
public interface IService
{
 [OperationContract]
 [WebGet(UriTemplate = "NewUri/?value={value}", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
 string GetData(int value);
 [WebGet(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
 [OperationContract]
 List<Student> GetStudentList();

}
  • In web config, start with changing "wsHttpBinding" to "webHttpBinding" (we are not working with Web Services now), then add the whole section below with our self-named behavior "JsonBehavior". Now add the behaviorConfiguration="JsonBehavior" attribute to the service-tag.
<system.serviceModel>
 <services>
   <service name="Service" behaviorConfiguration="ServiceBehavior">
     <endpoint address="" binding="webHttpBinding" behaviorConfiguration="JsonBehavior" bindingConfiguration="" contract="IService"/>
   </service>
 </services>
 <behaviors>
   <endpointBehaviors>

     <behavior name="JsonBehavior">
       <webHttp />
     </behavior>
   </endpointBehaviors>
   <serviceBehaviors>
     <behavior name="ServiceBehavior">
       <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
       <serviceMetadata httpGetEnabled="true"/>
       <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
       <serviceDebug includeExceptionDetailInFaults="false"/>
     </behavior>
   </serviceBehaviors>
 </behaviors>
</system.serviceModel>
</configuration>
Here is the complete source code IService.cs
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;


[ServiceContract]
public interface IService
{
  [OperationContract]
  [WebGet(UriTemplate = "NewUri/?value={value}", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
  string GetData(int value);
  [WebGet(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
  [OperationContract]
  List<Student> GetStudentList();

}
[DataContract]
public class Student
{
  [DataMember]
  public int StudentId { get; set; }
  [DataMember]
  public string StudentName { get; set; }
  [DataMember]
  public int Marks1 { get; set; }
  [DataMember]
  public int Marks2 { get; set; }
  [DataMember]
  public string EmailAddress { get; set; }
}

Service.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

// NOTE: If you change the class name "Service" here, you must also update the reference to "Service" in Web.config and in the associated .svc file.
public class Service : IService
{
  public string GetData(int value)
  {
      return string.Format("You entered: {0}", value);
  }
  /// <summary>
  /// Return List of student.
  /// </summary>
  /// <returns></returns>
  public List<Student> GetStudentList()
  {

      List<Student> students = new List<Student>()
         {  new Student{StudentId=1,StudentName="S#001",Marks1=10,Marks2=20,EmailAddress="student1@st.com"},
             new Student{StudentId=2,StudentName="S#002",Marks1=9,Marks2=30, EmailAddress="student2@st.com"},
             new Student{StudentId=3,StudentName="S#003",Marks1=11,Marks2=20,EmailAddress="student3@st.com"},
             new Student{StudentId=4,StudentName="S#004",Marks1=20,Marks2=30,EmailAddress="student4@st.com"},
             new Student{StudentId=5,StudentName="S#005",Marks1=9,Marks2=40,EmailAddress="student5@st.com"},
             new Student{StudentId=6,StudentName="S#006",Marks1=30,Marks2=50,EmailAddress="student6@st.com"},
         };
      return students;

  }
}
Default.aspx
<%@ 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">
      $().ready(function() {
          $("#btnStudent").click(function() {
              $.getJSON("Service.svc/GetStudentList", function(data) {
                  BuildTable(data);
              });
          });

          $("#myButt").click(function() {
              var num = $("#name").val();
              $.getJSON("Service.svc/NewUri", { value: num }, function(data) {
                  alert(data);
              });
          });
      });
      function BuildTable(data) {
          var table = '<table><thead><tr><th>StudentID</th><th>StudentName</th><th>Marks1</th></thead><tbody>';

          $.each(data, function(i, student) {
              var row = '<tr>';
              row += '<td>' + student.StudentId + '</td>';
              row += '<td>' + student.StudentName + '</td>';
              row += '<td>' + student.Marks1 + '</td>';
              row += '</tr>';
              table += row;
          });
          table += '</tbody></table>';
          $('#Container').html(table);
      }
  </script>

</head>
<body>
  <form id="form1" runat="server">
  <div>
      <input type="button" value="Get values from server" id="myButt" />
      <input type="button" value="GetStudentList" id="btnStudent" />
      <p>
          <input type="text" id="name" value="1" /><br />
      </p>
  </div>
  <div id="Container">
  </div>
  </form>
</body>
</html>
Service.svc
<%@ ServiceHost Language="C#" Debug="true" Service="Service" CodeBehind="~/App_Code/Service.cs" %>