Scenario:
In your web application data entry form, suppose you have a drop-down list from which user has to select an option, and on the basis of his/her selection you want to populate other drop-down list or field ( just like on selection of one category name from drop-down list you want to show/populate related products in other drop-down list ).
Calling web service using java script reduces post back and server round trip.
In this example we will access web service written in C# from client side by using java script and Web Service behaviour. I have used Categories, Products and Suppliers tables of Northwind database supplied by Microsoft with MS Access or Visual Studio.
Requirements:
- Data Layer : defines functions to retrieve data from database [Optional : you can directly access database from the web method]
- Web Service: defines web method that can be accessed across the internet.
- Java Script: defines functions to call web method.
- webservice.htc file, and: It is an html component file which encapsulates web service behaviour, that can be attached with any form elements using the style attribute. The web service behaviour helps you to use web service without the knowledge of SOAP and, enables client-side script to access a Web Service without navigating to another URL. It provides you to call web method, synchronously and asynchronously. The default mode of remote method call is asynchronous.
- HTML form: to show the result of the web method.
- .Net Framework 1.0
Data Layer Class: This class has three main functions : GetAllCategories, GetProducts and GetSuppliers.
The GetAllCategories function retrieves categoryid and categoryname of all categories from Category Table. This function is used to populated category drop-down list in page load event.
The GetProducts function retrieves productid and productname of all the products of specific category from Products Table.
The GetSuppliers function retrieves supplierid and companyname of supplier of specific product from suppliers table.
// DataLayer.cs
using System;
using System.Data ;
using System.Data.SqlClient ;
namespace JSWebService
{
/// <summary>
/// Summary description for DataLayer.
/// </summary>
public class DataLayer
{
private static SqlConnection _objConnection;
private static SqlDataAdapter _objDataAdapter;
private static string strConnectionString;
private static void OpenConnection()
{
try
{
if ( _objConnection == null)
{
//Change connection string as per your requirement.
strConnectionString = "server=avi; uid=sa; pwd=; database=northwind";
_objConnection = new SqlConnection (strConnectionString);
_objConnection.Open ();
}
}
catch ( Exception e)
{
throw new Exception ("Error in opening connection : " + e.Message );
}
}
private static void CloseConnection()
{
try
{
if ( _objConnection != null)
{
_objConnection.Close ();
_objConnection = null;
}
}
catch (Exception e)
{
throw new Exception ("Error in closing connection : " + e.Message );
}
}
public static void GetAllCategories(DataSet p_DataSetCategory)
{
try
{
OpenConnection();
_objDataAdapter = new SqlDataAdapter ("select categoryID, categoryName from categories", _objConnection);
_objDataAdapter.Fill (p_DataSetCategory,"Categories");
_objDataAdapter = null;
CloseConnection();
}
catch (Exception e)
{
throw new Exception ("Error :: " + e.Message );
}
}
public static void GetProducts(DataSet p_DataSetProducts,int p_intCategoryID)
{
try
{
OpenConnection();
_objDataAdapter = new SqlDataAdapter ("select productID,productName from products where categoryID = " + p_intCategoryID , _objConnection);
_objDataAdapter.Fill (p_DataSetProducts,"Products");
_objDataAdapter = null;
CloseConnection();
}
catch (Exception e)
{
throw new Exception ("Error :: " + e.Message );
}
}
public static void GetSuppliers(DataSet p_DataSetSuppliers,int p_intProductID)
{
try
{
OpenConnection();
_objDataAdapter = new SqlDataAdapter ("select p.SupplierID,s.CompanyName from products p,suppliers s where p.SupplierId = s.SupplierId and p.ProductId = " + p_intProductID , _objConnection);
_objDataAdapter.Fill (p_DataSetSuppliers,"Suppliers");
_objDataAdapter = null;
CloseConnection();
}
catch (Exception e)
{
throw new Exception ("Error :: " + e.Message );
}
}
}
}
WebService Class: The web service class has three web methods : GetProductsForCategoryId and GetSuppliersForProductId.
The GetProductsForCategoryId method calls GetProducts function of datalayer to retrieve records of specified categoryId. It stores result in an array of string and returns the same to callback function.
The GetSuppliersForProductId method calls GetSuppliers function of datalayer to retrieve records of specified productId. It stores result in an array of string and returns the same to callback function.
// ProductWebService.cs
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient ;
using System.Diagnostics;
using System.Web;
using System.Web.Services;
using DataLayer;
using System.Xml ;
namespace JSWebService
{
/// <summary>
/// Summary description for ProductWebService.
/// </summary>
public class ProductWebService : System.Web.Services.WebService
{
public ProductWebService()
{
//CODEGEN: This call is required by the ASP.NET Web Services Designer
InitializeComponent();
}
[WebMethod]
public string[] GetSuppliersForProductId(int p_intProductId)
{
DataSet _dsSuppliers;
_dsSuppliers = new DataSet ();
DataLayer.GetSuppliers ( _dsSuppliers,p_intProductId);
if (_dsSuppliers.Tables[0].Rows.Count > 0)
{
int _recordCount = _dsSuppliers.Tables[0].Rows.Count*2 ;
string[] _productsList = new string [_recordCount];
_recordCount = 0;
foreach(DataRow _drSupplier in _dsSuppliers.Tables[0].Rows )
{
_productsList[_recordCount] = _drSupplier[0].ToString ();
_recordCount += 1;
_productsList[_recordCount] = _drSupplier[1].ToString ();
_recordCount += 1;
}
return _productsList;
}
else
{
return null;
}
}
// this web method that will return list suppliers related to
// specified productId, in the form of array of string
[WebMethod(true)]
public String[] GetProductsForCategoryId(int p_intCategoryID)
{
DataSet _dsProducts;
_dsProducts = new DataSet ();
DataLayer.GetProducts ( _dsProducts,p_intCategoryID);
if (_dsProducts.Tables[0].Rows.Count > 0)
{
int _recordCount = _dsProducts.Tables[0].Rows.Count*2 ;
string[] _productsList = new string [_recordCount];
_recordCount = 0;
foreach(DataRow _drProduct in _dsProducts.Tables[0].Rows )
{
_productsList[_recordCount] = _drProduct[0].ToString ();
_recordCount += 1;
_productsList[_recordCount] = _drProduct[1].ToString ();
_recordCount += 1;
}
return _productsList;
}
else
{
return null;
}
}
#region Component Designer generated code
//Required by the Web Services Designer
private IContainer components = null;
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if(disposing && components != null)
{
components.Dispose();
}
base.Dispose(disposing);
}
#endregion
}
}

prasad thallaPosted Jul 19, 2007, 8:05 AM
Hi Kumar, I have one jsp application. In that there is JSP login page is there . when the user logins in login page he will move next page in that page there is 2 frame sets in my application. first frame set is jsp application (Login , logout, home are in one frame set) this is common for all pages and this application is running in one server . This server is maintaining sessions for that user. 2nd frame set is for asp.net(c#) Pages this is in different server. Problem : when the user is try to login I want to maintain these all values in sessions. I am reading values in aspx page through querystrings ge there I am assigning these query string to sessions . but I am reading these query string in aspx page but when I try to assign these querystrings to sessions it is not working .(I am losing session within a second) Please give me direction Regards Prasad Talla
Jim PetersoneditedPosted Jan 3, 2006, 10:41 AMEdited Jan 3, 2006, 10:42 AM
If you want your code to be formatted correctly, copy it from Visual Studio into MS word, and then onto C# Corner. It should have the correct indentation, etc.