Thursday, September 4, 2008

GridView Javascript Click Row and Webservice




This post shows 2 common tasks with the ASP.NET GridView: Binding a List (generic) of objects as DataSource and on clicking a row, getting the values of the selected row by a javascript function. In the example a List with User-objects is displayed. On clicking a row containing the data of a User-object, the Id of the object is used to get the address of the user by an Ajax-call and display it in a details-field.

Binding objects to a GridView in ASP.NET is a well supported feature. You need to add the objects you like to bind to a Collection like an IList<> and assign the list as datasource to the GridView. The mechanism of binding works by reading out the properties of the bound objects. Each property of your object maps to a column in the GridView.

So binding and displaying your data isn't very hard. A little more tricky is the procedure to refer to your data in a client-script. There are some use-cases where you need this, for example when you want to get some detail-information that correspond to the selected row, but don't want to reload the page for that. In our sample-project we get the address of the selected user by executing a Webservice-call and display the information in a DIV-element.

Binding the List

First we define a User and Address-object for binding to a GridView:(in App_Code Folder)

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// User
/// </summary>
public class User
{

/// <summary>
/// ctor
/// </summary>
/// <param name="name"></param>
/// <param name="description"></param>
public User(string name, string description)
{
   _name = name;
   _description = description;
   _id = Guid.NewGuid().ToString();
}

private string _id;

public string Id
{
   get { return _id; }
   set { _id = value; }
}

private string _name;

public string Name
{
   get { return _name; }
   set { _name = value; }
}
private string _description;

public string Description
{
   get { return _description; }
   set { _description = value; }
}
}

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// Summary description for Address
/// </summary>
public class Address
{
public Address(string street, string location, string zipCode)
{
    _street = street;
    _location = location;
    _zipCode = zipCode;
}

private string _street;
public string Street
{
    get { return _street; }
    set { _street = value; }
}

private string _location;
public string Location
{
    get { return _location; }
    set { _location = value; }
}

private string _zipCode;
public string ZipCode
{
    get { return _zipCode; }
    set { _zipCode = value; }
}

public override string ToString()
{
    string result = "";

    result += "Street: " + _street + "<BR/>";
    result += "Location: " + _location + "<BR/>";
    result += "ZipCode: " + _zipCode + "<BR/>";


    return result;
}


}
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="PageMethods.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>GridView, javascript and Webservice</title>

 <script type="text/javascript">
       /**
              * a user has been clicked
              * @param userId id of the user
              * Now we defined that whenever a DataRow is clicked,
              * the javascript-function CallMyWebService is called. 
              * And here is the function in the head of the aspx-page:
              */
      function CallMyWebService( userId)
     {

       PageMethods.GetAddressForUser(userId, OnRequestComplete);
     }
   function OnRequestComplete(result)
      {
        document.getElementById('addressBox').innerHTML = result;
     }
 </script>

</head>
<body style="font-family: Tahoma">
 <form id="frmMain" runat="server">
     <asp:ScriptManager ID="ScriptManger1" runat="Server" EnablePageMethods="true">
     </asp:ScriptManager>
     <div>
         <h1>
             GridView, javascript and Ajax</h1>
         <span style="font-size: 10pt"><strong>Users:</strong></span><br />
         <asp:GridView ID="GridView1" runat="server" BackColor="LightGoldenrodYellow" BorderColor="Tan"
             BorderWidth="1px" CellPadding="2" Font-Names="Tahoma" ForeColor="Black" GridLines="None"
             Width="300px" OnRowDataBound="GridView1_RowDataBound" AutoGenerateColumns="False">
             <FooterStyle BackColor="Tan" />
             <SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />
             <PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue" HorizontalAlign="Center" />
             <HeaderStyle BackColor="Tan" Font-Bold="True" />
             <AlternatingRowStyle BackColor="PaleGoldenrod" />
             <Columns>
                 <asp:BoundField DataField="Id" Visible="False" />
                 <asp:BoundField DataField="Name" HeaderText="Name">
                     <HeaderStyle HorizontalAlign="Left" />
                 </asp:BoundField>
                 <asp:BoundField DataField="Description" HeaderText="Description">
                     <HeaderStyle HorizontalAlign="Left" />
                 </asp:BoundField>
             </Columns>
         </asp:GridView>
         <br />
         <span style="font-size: 10pt"><strong>User's address:</strong></span><br />
         <div style="width: 300px; height: 80px; background-color: Beige">
             <div style="margin: 5px 5px 5px 5px" id="addressBox">
             </div>
         </div>
     </div>
 </form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;

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


      if (!Page.IsPostBack)
      {
          BuildUserList();
      }
  }

  private void BuildUserList()
  {
      IList<User> users = new List<User>();
      users.Add(new User("Xyz", "Coder"));
      users.Add(new User("Abc", "Writer"));
      users.Add(new User("Charles", "Poet"));

      // assign users to GridView
      GridView1.DataSource = users;
      GridView1.DataBind();


      // Store some sampledata
      Dictionary<string, Address> addresses = new Dictionary<string, Address>();
      addresses.Add(users[0].Id, new Address("Teststreet", "Stuttgart", "83840"));
      addresses.Add(users[1].Id, new Address("India", "Delhi", "23455"));
      addresses.Add(users[2].Id, new Address("Abc", "Bangalore", "34566"));

      Session["Addresses"] = addresses;

  }

  protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
  {
      if (e.Row.RowType == DataControlRowType.DataRow)
      {
          User selUser = e.Row.DataItem as User;
          e.Row.Attributes.Add("onclick", "CallMyWebService('" + selUser.Id + "')");
      }
  }

  [System.Web.Services.WebMethod]
  [System.Web.Script.Services.ScriptMethod]
  public static string GetAddressForUser(string userId)
  {
      Dictionary<string, Address> addresses = HttpContext.Current.Session["Addresses"] as Dictionary<string, Address>;

      Address address = addresses[userId];
      return address.ToString();
  }
}

No comments:

Post a Comment