Shalvin Interests

Tuesday, March 29, 2016

JQuery Ajax : Consuming Array of JSON

In this blog I am going to demonstrate consuming a Web Service which exposes the data from a table as JSON.



public class Contacts
{
    public int ContactId { get; set; }
    public string ContactName { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }
}

using System;
using System.Collections.Generic;
using System.Web.Services;
using System.Data.SqlClient;
using System.Web.Script.Serialization;

/// <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 void GetContacts() {
        List<Contacts> glCG = new List<Contacts>();

        SqlConnection cnn = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=SimpleContactManagement;Integrated Security=True");
        cnn.Open();
        SqlCommand cmd = new SqlCommand("select * from Contacts", cnn);
        SqlDataReader dr = cmd.ExecuteReader();

        while(dr.Read())
        {
            int intConId = Int32.Parse(dr["ContactId"].ToString());
            Contacts c = new Contacts
            {
                ContactId = intConId,
                ContactName = dr["ContactName"].ToString(),
                Email = dr["Email"].ToString(),
               Phone = dr["Phone"].ToString()
            };
            glCG.Add(c);
        }

        JavaScriptSerializer sc = new JavaScriptSerializer();
        Context.Response.Write(sc.Serialize(glCG));
    }
    
}


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="Scripts/jquery-1.12.1.js"></script>
    <script>
        $(document).ready(function () {
            getData();
        });

        function getData()
        {
            $.ajax(
                {
                    url: 'WebService.asmx/GetContacts',
                    dataType: "json",
                    method: 'post',
                    success: function (data) {
                        var contactsTable = $('#tblContacts tbody');
                        contactsTable.empty();

                        $(data).each(function (index, con) {
                            contactsTable.append('<tr><td>' + con.ContactId +
                                '</td><td>' + con.ContactName +
                                '</td><td>' + con.Email +
                                '</td><td>' + con.Phone +
                                '</td></tr>');
                        });
                    }
                });

            }
    </script>
</head>
<body>
    <table id="tblContacts">
        <thead>
            <tr>
                <th>Id</th>
                <th>Name</th>
                <th>Email</th>
                <td>Phone</td>
            </tr>
         </thead>
        <tbody>

        </tbody>
    </table>
</body>
</html>



JQuery Ajax and Json Array


using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Web.Services;
using System.Web.Script.Serialization;

[WebMethod]
    public void GetEmployees()
    {
        List<Employee> glEmployee = new List<Employee>();
        SqlConnection cnn = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=AjaxDb;Integrated Security=True");
        cnn.Open();
        SqlCommand cmd = new SqlCommand("select * from tblEmployee", cnn);
        SqlDataReader dr = cmd.ExecuteReader();
        while( dr.Read())
        {
            int intEmpId = Int32.Parse(dr["Id"].ToString());
            int intSalary = Int32.Parse(dr["Salary"].ToString());
            Employee emp = new Employee
            {
                Id = intEmpId,
                Name = dr["Name"].ToString(),
                Gender = dr["Gender"].ToString(),
                Salary = intSalary
            };
        glEmployee.Add(emp);

        }
      
        JavaScriptSerializer jsc = new JavaScriptSerializer();
        Context.Response.Write(jsc.Serialize(glEmployee));
    }



<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="Scripts/jquery-1.12.1.js"></script>
    <script>
    $(document).ready(function () {
        getData()
    });
  
    function getData()
    {
        $.ajax({
            url: 'WebService.asmx/GetEmployees',
            dataType: "json",
            method: 'post',
            success: function (data) {
                var employeeTable = $('#tblEmployee tbody');
                employeeTable.empty();

                $(data).each(function (index, emp) {
                    employeeTable.append('<tr><td>' + emp.Id + '</td><td>'
                        + emp.Name + '</td><td>' + emp.Gender
                        + '</td><td>' + emp.Salary + '</td></tr>');
                });
            },
            error: function (err) {
                alert(err);
            }
        });
    }
    </script>
</head>
<body>
    <table id="tblEmployee" border="1" style="border-collapse:collapse">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Gender</th>
                <th>Salary</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
</body>
</html>

Tuesday, March 15, 2016

JQuery Basic Filters and Asp .Net GridView


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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link href="StyleSheet.css" rel="stylesheet" />
    <script src="Scripts/jquery-1.12.1.js"></script>
    <script>
        $(document).ready(function () {

            $("#btnMark").click(function (evt) {
                var target = $("#ddl").val();

                $(".Highlight").removeClass("Highlight");

                switch (target) {
                    case "FR":
                        $("tr:first").addClass("Highlight");
                        break;
                    case "LR":
                        $("tr:last").addClass("Highlight");
                        break;
                    case "OD":
                        $("tr:odd").addClass("Highlight");
                        break;
                    case "EV":
                        $("tr:even").addClass("Highlight");
                        break;

                }

                evt.preventDefault();
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <asp:Label ID="Label1" runat="server" Text="Mark Rows"></asp:Label>
        <asp:DropDownList ID="ddl" runat="server">
            <asp:ListItem Value="FR">First Row</asp:ListItem>
            <asp:ListItem Value="LR">Last Row</asp:ListItem>
            <asp:ListItem Value="OD">Odd</asp:ListItem>
            <asp:ListItem Value="EV">Even</asp:ListItem>
        </asp:DropDownList>
&nbsp;&nbsp;
        <asp:Button ID="btnMark" runat="server" Text="Mark" />
        <br />
    
    </div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
            <Columns>
                <asp:BoundField DataField="FirstName" HeaderText="First Name" />
                <asp:BoundField DataField="LastName" HeaderText="Last Name" />
                <asp:BoundField DataField="Country" HeaderText="Country" />
            </Columns>
        </asp:GridView>
    </form>
</body>
</html>


NorthwindEntities ctx = new NorthwindEntities();
    protected void Page_Load(object sender, EventArgs e)
    {
        GridView1.DataSource = ctx.Employees.ToList();
        DataBind();
    }

Asp .Net RadioButtonList and JQuery


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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="jquery-1.12.1.js"></script>
    <script>
        $(document).ready(function()
        {
            $("#btnSubmit").click(
                function (evt) {
                    var result = $('input[type="radio"]:checked');
                    if(result.length > 0)
                    {
                        $("#Panel1").html(result.val() + " is checked");
                    }
                    return false;
                });
        });
        
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <asp:RadioButtonList ID="RadioButtonList1" runat="server">
            <asp:ListItem>Male</asp:ListItem>
            <asp:ListItem>Female</asp:ListItem>
        </asp:RadioButtonList>
        <br />
        <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
    
    </div>
        <asp:Panel ID="Panel1" runat="server">
        </asp:Panel>
    </form>
</body>
</html>

JQuery Basic Selectors


<html>
<head>
    <title></title>
    

    <script src="jquery-1.12.1.js"></script>
    <script>
        $(document).ready(
            function () {
                $("#btnNoRow").click(function()
                {
                    alert($('tr').length);
                });

                $("#btnNoData").click(function () {
                    alert($('td').length);
                });

                $("#btnRed").click(function () {
                   $('tr').css('background-color', 'red')
                });

                $("#btnTable").click(function () {
                    alert($('table').html())
                });

                $("#btnData").click(function () {
                    alert($('table').text())
                });
            });
    </script>
</head>
<body>
    <table border="1">
        <tr>
            <td>Shalvin</td>
            <td>Praseed</td>
            <td>Vaisakh</td>
        </tr>
        <tr>
            <td>Biju</td>
            <td>Joshy</td>
            <td>Akhil</td>
        </tr>
        <tr>
            <td>Merin</td>
            <td>Soorya</td>
            <td>Sreelakshmi</td>
        </tr>
        <tr>
            <td>Simi</td>
            <td>Simon</td>
            <td>Shibin</td>
        </tr>
        <tr>
            <td>JavaScript</td>
            <td>JQuery</td>
            <td>AngularJS</td>
        </tr>
    </table>
    <br /><br />
    <div>
        DIV 1
        <br />
        <a href="http://shalvinpd.blogspot.com">Shalvin P D</a>
    </div>
    <br /><br />
    <a href="http://google.com">Google</a>
    <br /><br />
    <div>DIV 2</div>
    <br /><br />
    <span>SPAN 1</span>
    <br /><br />
    <div>DIV 3</div>

    <input id="btnNoRow" type="button" value="No of Table Rows" />

    <input id="btnNoData" type="button" value="No of Table Datas" />

    <input id="btnRed" type="button" value="Make Table Red" />

    <input id="btnTable" type="button" value="Show Table" />

    <input id="btnData" type="button" value="Show Table Data" />
</body>
</html>