Monday, November 30, 2009

Calling an ASP.Net Web Service from Javascript


Page which calls the service has to have Script Manager and the Script Manager has to mention the ServiceReference attribute.

ScriptManager runat="server" ID="ScrpMgr1">
ScriptManagers>

Also, the Web.config file should have an extra entry for ScriptHandlerFactory.

System.Web.Script.Services.ScriptHandlerFactory" />

Below is my JavaScript method which calls the WebService. This has got a SuccessCallBack method to which the Service returns the result set.

var DivIDAct;
function MyWebServiceCallForActuals(ActualsDivId, BudgetYear, BudgetVersion, SalesDivision, row, Display)
{
expandcollapse(ActualsDivId, row, 2);
BrandSerivces.GetBrandsForActuals(BudgetYear, BudgetVersion, SalesDivision, '', SuccessCallBackActuals);
ActualsDivId = 'Division' + ActualsDivId;
var ActualsDivObj = document.getElementById(ActualsDivId);
DivIDAct = ActualsDivObj;
}

function SuccessCallBackActuals(result)
{
DivIDAct.innerHTML = result;
}

This is just to show an Expand Collapse button on click of each row item. A new row item would be displayed under the clicked row, which will show the details of the current row. The Javascript ExpandCollapse method takes care about swaping the Expand(Plus Image) and Collapse(Minus image) images. I am not going to explain much about this as this is self explanatory, just walk through the code.

function expandcollapse(obj, row, ch) {

var div;
var img;
if (ch == 1) {
div = document.getElementById('Div' + obj);
img = document.getElementById('img' + obj);
} else if (ch == 2) {
div = document.getElementById('Division' + obj);
img = document.getElementById('imgActuals' + obj);
}

if (div.style.display == "none") {
div.style.display = "block";
if (row == 'alt') {
img.src = "../App_Themes/Two/images/minus.gif";
}
else {
img.src = "../App_Themes/Two/images/minus.gif";
}
img.alt = "Close to view other Details";
}
else {
div.style.display = "none";
if (row == 'alt') {
img.src = "../App_Themes/Two/images/plus.gif";
}
else {
img.src = "../App_Themes/Two/images/plus.gif";
}
img.alt = "Expand to show Details";
}
}


Make a Dynamic Javascript Function Call from the ASP.Net Gridview Template fields.


Keep an Empty Div in a new Template Field where the Web Service result set (This result set would be returned by the SuccessCallBack method of javascript.) would be displayed. A detailed table for the corresponding row item.

<>
<div id="Division" style="overflow: auto; width: 100%">div>


No comments: