Showing posts with label Json. Show all posts
Showing posts with label Json. Show all posts

Wednesday, August 22, 2012

Make ajax calls using jquery to bind dropdownlist

Introduction

This article describes how to make AJAX calls using Jquery to bind databound control like dropdownlist with data from database. To Bind the data to any databound control, return data as json format.

Default.aspx

<script type="text/javascript">
        $(document).ready(function () {
            //Retrieve data and bind to dropdownlist
            $.ajax({
                url: "../Services/BookService.asmx/GetBooks",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                type: "POST",
                data: {},
                error: function (err) {
                    alert("Error:" + err.toString());
                },
                success: function (data) {
                    $("#booksList").html(data);
                    $.each(data.d, function (key, value) {
                        $("#<%=ddlBooks.ClientID %>").append($("<option></option>").val(value.ID).html(value.BookName));
                    });
                }
            });
        });
    </script>

<div>
        <asp:DropDownList ID="ddlBooks" runat="server">
        <asp:ListItem>Choose...</asp:ListItem>
        </asp:DropDownList>
        <asp:Button ID="btnGetBooks" runat="server" Text="Get Books" onclick=" btnGetBooks_Click" />
    </div> 

It is important to register the client script for event validation, since we bind the dropdownlist dynamically using client script it should be registered for event validation. Otherwise, the page will raise an error on postback. Though there is a possibility to bypass this scenario by setting either,

<%@ Page EnableEventValidation="false">

or Globally in the Web.config

<pages enableEventValidation="false"></pages>

The setting above may allow hackers to inject sql commands making the application vulnerable. To overcome this problem during the override the Render method as shown below.

Default.aspx.cs

protected override void Render(HtmlTextWriter writer)
    {
        ClientScript.RegisterForEventValidation(ddlBooks.UniqueID,"1");
        ClientScript.RegisterForEventValidation(ddlBooks.UniqueID, "2");
        ClientScript.RegisterForEventValidation(ddlBooks.UniqueID, "3");
        base.Render(writer);
    }

App_Code/Books.cs
public class Books
{
public Books()
{

}
    public string ID { get; set; }
    public string BookName { get; set; }
    public string Author{ get; set; }
}

Don't forget to uncomment the line shown below in the .asmx file if it does not exists add one.This enables us to make asynchronous calls to the function.

[System.Web.Script.Services.ScriptService]

App_Code/BookService.cs
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

// SQL Server Connection String
    SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString);

[WebMethod]
    public List<Books> GetBooks()
    {
        DataTable dtBooks = new DataTable();
        List<Books> books = new List<Books>();
        SqlDataAdapter adpBooks = new SqlDataAdapter("GetBooks", sqlcon);
        adpBooks.SelectCommand.CommandType = CommandType.StoredProcedure;
        //adpBooks.SelectCommand.Parameters.AddWithValue("@BookId", bookId);
        try
        {
            adpBooks.Fill(dtBooks);
            Books book;
            foreach (DataRow dr in dtBooks.Rows)
            {
                book = new Books();
                book.ID = dr["ID"].ToString();
                book.BookName = dr["Name"].ToString();
                book.Author = dr["Author"].ToString();
                books.Add(book);
            }
            return books;
        }
        catch (Exception)
        {
            throw;
        }
        finally
        {
            sqlcon.Close();
        }
    }

Tuesday, June 19, 2012

Serialize JSON string using asp.net and Jquery

As web applications are highly responsive, with asynchronous request to the sever and back to the client. In order to achieve flicker-free effect on web pages the request made to the server is asynchronous. Therefore the data sent to the browser should be in certain format (in our case JSON). Serialize the JSON string before being sent to the web browser.

App_Data/Persons.xml
<?xml version="1.0" encoding="utf-8" ?>
<persons>
    <person id="p101">
        <name>Aisha, Kumari</name>
        <age>28</age>
        <sex>female</sex>
        <nationality>India</nationality>
        <date_of_birth>2000-10-01</date_of_birth>
        <description> Sales manager </description>
    </person>
    <person id="p102">
        <name>Jonathan, Trott</name>
        <age>41</age>
        <sex>male</sex>
        <nationality>United states</nationality>
        <date_of_birth>2000-12-16</date_of_birth>
        <description> A former architect. </description>
    </person>
    <person id="p103">
        <name>Angelina, Jolie</name>
        <age>32</age>
        <sex>female</sex>
        <nationality>United states</nationality>
        <date_of_birth>2000-11-17</date_of_birth>
        <description> Technical operator. </description>
    </person>
    <person id="p104">
        <name>Jagatheesh, Pandian</name>
        <age>35</age>
        <sex>male</sex>
        <nationality>India</nationality>
        <date_of_birth>2001-03-10</date_of_birth>
        <description> Software Engineer. </description>
    </person>
    <person id="p105">
        <name>Jacob,John</name>
        <age>25</age>
        <sex>male</sex>
        <nationality>England</nationality>
        <date_of_birth>2001-09-10</date_of_birth>
        <description> Cheif Executive. </description>
    </person>
    <person id="p106">
        <name>Cynthia, Myriam</name>
        <age>29</age>
        <sex>female</sex>
        <nationality>China</nationality>
        <date_of_birth>2000-09-02</date_of_birth>
        <description> Operations manager. </description>
    </person>
    <person id="p107">
        <name>Nixon, Paul</name>
        <age>45</age>
        <sex>male</sex>
        <nationality>England</nationality>
        <date_of_birth>2000-11-02</date_of_birth>
        <description> A deep sea diver. </description>
    </person>
    <person id="p108">
        <name>Knorr, Stefan</name>
        <age>54</age>
        <sex>male</sex>
        <nationality>United states</nationality>
        <date_of_birth>2000-12-06</date_of_birth>
        <description> Technical Mentor. </description>
    </person>
    <person id="p109">
        <name>Kress, Peter</name>
        <age>43</age>
        <sex>male</sex>
        <nationality>India</nationality>
        <date_of_birth>2000-11-02</date_of_birth>
        <description> Artist. </description>
    </person>

    <person id="p110">
        <name>O'Brien, Tim</name>
        <age>33</age>
        <sex>male</sex>
        <nationality>Ireland</nationality>
        <date_of_birth>2000-12-09</date_of_birth>
        <description> Programmer. </description>
    </person>
</persons>

App_Code/Person.cs
public class Book
{

    /// <summary>
    /// do not change or remove "id", "value" and the "label" variables as atuocomplete need them to be sent    ///back
    /// </summary>
    public string id { get; set; }
    public string label { get; set; }
    public string value { get; set; }
 
    public string Name{get;set;}
    public string Age{ get; set; }
    public string Sex{ get; set; }
    public string Nationality{ get; set; }
    public string Date_of_birth{ get; set; }
    public string Description { get; set; }
}

PersonAutocomplete.ashx
<%@ WebHandler Language="C#" Class="AutoComplete" %>
using System;
using System.Collections.ObjectModel;
using System.Data;
using System.Web;
using System.Web.Script.Serialization;

public class AutoComplete : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        //  Query string 'term' is for autocomplete. By default, it sends the variable
        //  "term" with the search word to the backend page.
        string searchText = context.Request.QueryString["term"];

        Collection<Person> persons= new Collection<Person>();

        DataSet ds = new DataSet();
        ds.ReadXml(HttpContext.Current.Server.MapPath("App_Data/Persons.xml"));
        DataView dv = ds.Tables[0].DefaultView;
        dv.RowFilter = String.Format("title like '{0}*'", searchText.Replace("'", "''"));

        Person person;
        foreach (DataRowView myDataRow in dv)
        {
            person= new Person();
            person.id = myDataRow["id"].ToString();
            person.value = person.label = person.Name = myDataRow["name"].ToString();
            person.Age= myDataRow["age"].ToString();
            person.Sex= myDataRow["sex"].ToString();
            person.Nationality= myDataRow["nationality"].ToString();
            person.Date_of_birth = myDataRow["date_of_birth"].ToString();
            person.Description = myDataRow["description"].ToString();
            persons.Add(person);
        }

        JavaScriptSerializer serializer = new JavaScriptSerializer();

        string jsonString = serializer.Serialize(persons);

        context.Response.Write(jsonString);
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

Initially, reference the required Jquery library, Jquery UI library and the CSS in the head section as shown below.

Default.aspx
<link rel="stylesheet" href="Styles/jquery-ui.css" type="text/css" media="all" />
<link rel="stylesheet" href="Styles/site.css" type="text/css" />
<script type="text/javascript" src="Scripts/jquery.min.js"></script>
<script type="text/javascript" src="Scripts/jquery-ui.min.js"></script>
   
<script type="text/javascript">
        $(function () {
            $('#<%= tbBookName.ClientID %>').autocomplete({
                source: "PersonAutoComplete.ashx",
                select: function (event, ui) {
                    $(".name").text(ui.item.Name);
                    $(".age").text(ui.item.Age);
                    $(".sex").text(ui.item.Sex);
                    $(".date_of_birth").text(ui.item.Date_of_birth);
                    $(".description").text(ui.item.Description);
                }
            });
        });
    </script>

And, put the markup below in the body,

<form id="form1" runat="server">
    <h3>
        AutoComplete Example -- serialize JSON string and return search result
    </h3>
    <div class="search_bar">
        select book:
        <asp:TextBox ID="tbPersonName" runat="server" />
        (try a few examples like: 'Cynthia, Myriam', ' Kress, Peter')</div>
    <div class="search_response">
        <p>
            name: <span class="name"></span>
        </p>
        <p>
            age: <span class="age"></span>
        </p>
        <p>
            sex: <span class="sex"></span>
        </p>
        <p>
            date of birth: <span class="date_of_birth"></span>
        </p>
        <p>
            description: <span class="description"></span>
        </p>
    </div>
    </form>

Codeigniter Shield Authorization

Codeigniter Shield Authorization CodeIgniter Shield is the official authentication and authorization framework for CodeIgniter 4. It provide...