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

Wednesday, October 20, 2010

How to bind data in gridview using Jquery

#1. First of all create the html page or .aspx page than create a table in html. Then write the JavaScript code using ajax.
The following code you can see or you can paste the code in head tag:
    <script src="jquery-1.4.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready( function(){
            Demo.loadData();
        });
        function cleartext()
        {
            document.getElementById('txtContact').value = "";
            document.getElementById('txtCompany').value = "";
        }
        function addCustomer1()
        {
            contact = document.getElementById('txtContact').value;
            company = document.getElementById('txtCompany').value;
            if(contact.length != 0)
            {
                if(company.length != 0)
                {
                    Demo.AddCustomer(contact,company);
                    cleartext();
                }
            }
        }
    </script>
    <script type="text/javascript">
        Demo = {};
       
        //how to bind gridview using jquery in table form
        Demo.loadData = function () {
            Demo.AjaxRequest("AjaxServices.asmx/GetCustomer","{}",function(result){
                //alert(result);
                var results = eval('(' + result.d + ')');
                var dd = '';
                dd += '<table cellspecing="0" cellpadding="0" class="test">';
                dd += '<th>Customer Id</th><th>Contact Name</th><th>Company Name</th>';
                for(var i = 0; i < results.length ; i++)
                {
                    dd += '<tr><td>' + results[i].CustomerId + '</td><td>' + results[i].ContactName + '</td><td>' + results[i].CompanyName + '</td>';
                    dd += '</tr>';
                }
                dd += '</table>';
                $('#demo').empty()
                    .html(dd)
                    .slideDown('slow',function() {
                        window.scrollTo(0, $('#demo').height())
                    });
            },function(){
                alert('Error');
            });
        }
       
        //how to add data using jquery
        Demo.AddCustomer = function (contact, company) {
            Demo.AjaxRequest("AjaxServices.asmx/AddCustomer","{'contact':'" + contact + "','company':'" + company + "'}",function(result){
               var results = ('(' + result.d + ')');
               if(results == '("Success")')
                    Demo.loadData();
               else
                    alert('sql error');
               },function() {
                    alert('unknown error');
            });
        }
       
        //Function to cummunicate with database
        Demo.AjaxRequest = function (url, param, successfullcallback, errorcallback) {
            $.ajax({
                type: "POST",
                url: url,
                data: param,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: successfullcallback,
                error: errorcallback
            });
        }
    </script>

#2. Second thing apply styleseet code on the table. Copy the following code and then paste it in head tag:
<style type="text/css">
        .test{ width:100%; border-collapse:collapse; border:solid 1px #000; font-size:.95em;}
        .test th{background-color:black; color:White; padding:5px; border-left:solid 1px #000; border-bottom:solid 1px #000;  }
        .test td{ padding:5px;border-left:solid 1px #000; border-bottom:solid 1px #000;}
</style>


#3. Third thing is that create the html form in the page and create a table like this with id.
<table style="border:1px; border-color:Black;">
            <tr>
                  <td>
                        Contact Name :
                  </td>
                  <td>
                        <input type="text" id="txtContact" />
                  </td>
            </tr>
            <tr>
                  <td>
                        Company Name :
                  </td>
                  <td>
                        <input type="text" id="txtCompany" />
                  </td>
            </tr>
            <tr>
                  <td>
                        <input type="button" value="Submit" id="btnSubmit" onclick="addCustomer1()" />
                  </td>
                  <td>
                        <input type="button" value="Reset" id="btnClear" onclick="cleartext()" />
                  </td>
            </tr>
      </table>
      <div id="demo">
            This is a demo grid view.
      </div>

#4. Fourth one is that create the webservice.asmx file and write the code to communicate with database. The following code is helpful for you.
using System;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Web.Script.Services;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Script.Serialization;
using System.Data;

/// <summary>
/// Summary description for AjaxServices
/// </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]
[ScriptService()]
public class AjaxServices : System.Web.Services.WebService {

    //Add customer in the table
    [WebMethod]
    public string AddCustomer(string contact, string company)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Test"].ConnectionString);
        SqlCommand cmd = new SqlCommand("Insert into Customer(ContactName,CompanyName) Values(@cont,@comp) ", con);
        cmd.Parameters.AddWithValue("@cont", contact);
        cmd.Parameters.AddWithValue("@comp", company);
        con.Open();
        int i = (Convert.ToInt32(cmd.ExecuteNonQuery()));
        con.Close();
        string message = (i == 1) ? "Success" : "Faliur";
        return new JavaScriptSerializer().Serialize(message);
    }

    //The following code Binding the customer table
    [WebMethod]
    public string GetCustomer()
    {
        List<Customer> customer = new List<Customer>();
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Test"].ConnectionString);
        SqlCommand cmd = new SqlCommand("Select * from Customer", con);
        DataTable dt = new DataTable();
        con.Open();
        SqlDataAdapter adt = new SqlDataAdapter(cmd);
        adt.Fill(dt);
        con.Close();
        if (dt.Rows.Count > 0)
        {
            foreach (DataRow row in dt.Rows)
            {
                Customer newCustomer = new Customer();
                newCustomer.CustomerId = Convert.ToInt32(row["CustomerID"].ToString());
                newCustomer.ContactName = row["ContactName"].ToString();
                newCustomer.CompanyName = row["CompanyName"].ToString();
                customer.Add(newCustomer);
            }
            return new JavaScriptSerializer().Serialize(customer);
        }
        else
        {
            return new JavaScriptSerializer().Serialize("no customer");
        }
    }
}

public class Customer
{
    private Nullable<int> customerid = null;

    public Nullable<int> CustomerId
    {
        get { return customerid; }
        set { customerid = value; }
    }
    private string contactname = null;

    public string ContactName
    {
        get { return contactname; }
        set { contactname = value; }
    }

    private string companyname = null;

    public string CompanyName
    {
        get { return companyname; }
        set { companyname = value; }
    }
}
#5. First of all configure your web.config file for 2.0 frame work. If you work on 3.5 frame work then no problem with this code. And it will be execute successfully.





Sunday, October 17, 2010

How to insert data in database using jquery

#1. Configure your web.config file. Because of start scripting services.








#2. Make a page with html controls.
First one: Text boxes which can contain the data to be insert in database
Second one: Button control which click event insert the in the database using                                   jquery. 



<head runat="server">
    <title>How to add data in database using Jquery</title>
   
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
   
    <script type="text/javascript">
        $(document).ready(function () {
            $('#btnSubmit').click(function () {
                var name = $('#txtName').val();
                var age = $('#txtAge').val();
                $.ajax({
                    type: "POST",
                    url: "AjaxService.asmx/AddData",
                    data: "{'name':'" + name + "','age':'" + age + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function () {
                        $("#txtName").val() = "";
                        $("#txtAge").val() = "";
                        alert("Hello");
                    }
                });
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table>
            <tr>
                <td>
                    Enter your name :
                </td>
                <td>
                    <input type="text" id="txtName" />
                </td>
            </tr>
            <tr>
                <td>
                    Enter your Age :
                </td>
                <td>
                    <input type="text" id="txtAge" />
                </td>
            </tr>
            <tr>
                <td>
                    <input type="button" id="btnSubmit" value="Submit" />
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>




#3. Make a .asmx file where you write the code to database connectivity.

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

/// <summary>
/// Summary description for AjaxService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService()]
public class AjaxService : System.Web.Services.WebService {

    public AjaxService () {

        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }

    [WebMethod]
    public void AddData(string name, string age)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Test"].ConnectionString);
        con.Open();
        SqlCommand cmd = new SqlCommand("Insert into InsertData(Name,Age) Values(@name,@age)",con);
        cmd.Parameters.AddWithValue("@name", name);
        cmd.Parameters.AddWithValue("@age", age);
        cmd.ExecuteNonQuery();
        con.Close();
    }
}


Note: This code is for add data into database using jquery.
Without scripting services this will not run properly. So configure you web.config file to start scripting services.


#4. Create Database in ms sql server 2005
Create Database Test
Create Table InsertData(Name varchar(20),Age varchar(20))

#5. Thanks. If you like this then give me comment.


Download Full Code : http://rapidshare.com/files/425720577/JavaScriptUsingJquery.rar