Call PageMethod/WebMethod Using Jquery in ASP.Net

June 13, 2011

Normally as a ASP.Net developer, when its required to call a PageMethod or WebMethod from Client side always we prefer to use ASP.NET AJAX’s page methods. I discovered that you can call page methods via jQuery. In fact, it turns out that you can even do it without involving the ScriptManager at all.

In this post, I will explain exactly what is and isn’t necessary in order to use page methods. Then, I’ll show you how to use jQuery to call a page method without using the ScriptManager.

Lets Start then!!!!

The very first step you have to do is download Jquery File and add it to your project. You can download form here.

Add reference of “jquery-1.2.3.min.js” file to your page from where you want to call the server method.

Now i will explain you what you have to do when you want to call server method withount an argument, with a single argument and with multiple arguments.

I will provide you sample for each.

To make it very simple i have create a common javascript method, which you can place in master page so that the same may be use to call a server method from any page.

function CallServerMethod(PageName, PageMethodName, para, onSuccess)
{
$.ajax({
type: “POST”,

//Page Name (in which the method should be called) and method name
//url: “Default.aspx/CheckDateTime”,
url: PageName + “/” + PageMethodName,
// If you want to pass parameter or data to server side function you can try line
data: “{” + para + “}”,
//else If you don’t want to pass any value to server side function leave the data to blank line below
//data: “{}”,
contentType: “application/json; charset=utf-8”,
dataType: “json”,
success: onSuccess,
error: function(response)
{
alert(response.d);
}
});
}

Now Let say if you have three methods in your page. One with no argument, One with single argument and one with multiple arguments. As Shown in below.

[System.Web.Services.WebMethod()]
public static string GetName()
{
return “Return From Server: VIMAL”;
}

[System.Web.Services.WebMethod()]
public static string GetNameSingleArgu(string FirstName)
{
return “Return From Server: ” + FirstName;
}

[System.Web.Services.WebMethod()]
public static string GetNameMultipleArgu(string FirstName,string LastName)
{
return “Return From Server: ” + FirstName + ” ” + LastName;
}

Now to Call a Server Method without any argument, You just have to write the following Javascript Code:

function GetNameFromServer()
{
CallServerMethod(‘Default.aspx’,’GetName’,”,CallSuccessGetName);
}

function CallSuccessGetName(ReturnValue)
{
alert(ReturnValue.d);
}

If you are thinking about ReturnValue.d, be sure to visit post about what it is, why it’s there, and why you may not need it in your version of ASP.NET.

Simple!!! Very fist argument will be your Page/WebService Name and Second one will be Method Name. Last parameter is function name which you want to call upon success return from server method.

Third parameter is parameter values that you want to pass to the server method. To call server method with single argument you have to write the javascript code as below:

function GetNameFromServerWithSingleArgument()
{
var FirstName = “VIMAL”;
CallServerMethod(‘Default.aspx’,’GetNameSingleArgu’,”‘FirstName’:'” + FirstName + “‘”,CallSuccessGetName);
}

See carefully the format of third parameter is. It would be like this ‘ParameterName’:’ParameterValue’,’SecondParameterName’:’SecondParameterValue’…..

To Call a server method with multiple arguments do the following:

function GetNameFromServerWithMultipleArgument()
{
var FirstName = “VIMAL”;
var LastName = “PANCHAL”;
CallServerMethod(‘Default.aspx’,’GetNameMultipleArgu’,”‘FirstName’:'” + FirstName + “‘,’LastName’:'” + LastName + “‘”,CallSuccessGetName);
}

As you can see, there’s no ScriptManager required, much less EnablePageMethods.

That’s it from my side. I am attaching the sample code for your reference, which will also show you the way to call method from Web Service.

CallServerMethodUsingJquery

Note: Please rename above file from callservermethodusingjquery.doc to callservermethodusingjquery.zip.

If you have any doubt or issue feel free to contact me by commenting out here… 🙂

Enjoy Coding!!!!

Advertisements

Scanning 1D/2D Barcode from Windows Mobile using Integrated Camera

August 17, 2010

Here is the sample code which shows you how to Scan 1D/2D barcode from Windows Mobile using Integrated Camera.

In this sample i have used zxing.mobile open source library.

So, Just download the below file -> change its extension from ‘.doc’ to ‘.zip’ -> Open the project in Visual Studio 2008 -> Run.

ScanBarcode1D2D

Still i am working to on Generating 1D/2D barcode from Windows Mobile Application.


Autocomplete ComboBox (Windows Mobile)

July 7, 2010

Here is the code by which you can get functionality of Auto complete combobox in normal combobox.

Just set your combobox’s DropDownStyle to System.Windows.Forms.ComboBoxStyle.DropDown and add the following code in KeyUp event of the same combobox.

private void cbo_KeyUp(object sender, KeyEventArgs e)
{
string text = null;
int num = -1;
object item = null;
string str3 = null;
ComboBox box = (ComboBox)sender;
switch (e.KeyCode)
{
case Keys.Left:
case Keys.Up:
case Keys.Right:
case Keys.Down:
case Keys.Delete:
case Keys.Back:
return;

default:
text = box.Text;
for (int i = 0; i = 0)
{
item = box.Items[num];
str3 = box.GetItemText(item).Substring(text.Length);
box.Text = text + str3;
box.SelectionStart = text.Length;
box.SelectionLength = str3.Length;
box.SelectedItem = item;
}
}

That’s it!!!!!
Happy Windows Mobile Codding…. 🙂


Pass more than one Values(databinder.eval) to Javascript Functiont

May 3, 2010

In my previous one Post i written about how to pass a databinder.eval value to JavaScript function. It is showing that how can we pass a single value to JavaScript function but in some case we required to pass more than one values to JavaScript function. To do that we need to use String.Format.

Here is the Small Example for the same.

I have a Javascript Function by name ‘showValues’ with three Parameters like ID of type int, FirstName of type string and LastName of type string. i want to call this function on OnClientClick event of the LinkButton Control.

Here is my Javascript Function’s Definition:
function showValues(ID, FirstName, LastName)
{
   alert(ID + ‘,’ + FirstName+ ‘,’ + LastName);
   return false;
}

now to call this function i have added ‘OnClientClick’ event of the LinkButton like this in the Grid TemplateField:

<asp:TemplateField HeaderText=”LastName”>
  <ItemTemplate>
   <asp:LinkButton ID=”lnkClick”  OnClientClick='<%#String.Format(“return showValues({0},
&#39;{1}&#39;,&#39;{2}&#39;)”, Eval(“ID”),  Eval(“FirstName”),  Eval(“LastName”)) %>’  runat=”server”> <%# Eval(“LastName”) %>     </asp:LinkButton>
  </ItemTemplate>
</asp:TemplateField>

Click Here  to see how your OnClientClick event should be written.

Thats it!!!! 🙂
Enjoy Coddig……..


Highlighting Search Keywords in a HTML DIV Control Using Javascript

March 15, 2010

In many of the popular search engines (most of all ones), when you perform a search the resulting page displays the word(s) you searched on are highlighted different colors to make them easy to pick out.
This article will examine how to provide such functionality in HTML DIV control with the use of a simple javascript function.
Lets Start…….. 🙂

Here is the Javascript function will do that.

objDIV = Div which contains the Text Contents
textToHightLight = Text (Searched Word) which should be Highlighted

function innerHighlight(objDIV, textToHightLight)
{
var skip = 0;
if (objDIV.nodeType == 3)
{
var pos = objDIV.data.toUpperCase().indexOf(textToHightLight.toUpperCase());
if (pos >= 0)
{
var spannode = document.createElement(‘span’);
spannode.className = ‘highlight’;
var middlebit = objDIV.splitText(pos);
var endbit = middlebit.splitText(textToHightLight.length);
var middleclone = middlebit.cloneNode(true);
spannode.appendChild(middleclone);
middlebit.parentNode.replaceChild(spannode, middlebit);
skip = 1;
}
}
else if (objDIV.nodeType == 1 && objDIV.childNodes && !/(script|style)/i.test(objDIV.tagName))
{
for (var i = 0; i < objDIV.childNodes.length; ++i)
{
i += innerHighlight(objDIV.childNodes[i], textToHightLight);
}
}
return skip;
}

In the code note that i have set the className for the SPAN Element to 'highlight'. This HTML will apply the style of a particular class to the word we wish to highlight. Feel free to use whatever CSS markup you'd like to in order to have the search word "highlighted." The below CSS will give the highlighted word a yellow background.

.highlight {text-decoration: none;color:black;background:yellow;}

Happy codding!!!!!!!!!! 🙂


Pass Value(databinder.eval) to Javascript Function

July 15, 2009

In some scenario we have to call Javascript Function with dynamic parameter values.

Take a scenario in which we have to pass variables to javascript on ‘onchange; event of Textbox which is in TemplateColumn of gridview.

Here is the Small Example for the same.

I have a Javascript Function with the name ‘processRequest’ with three Parameters like sender of type object, columnName of type string and ID of type int. i want to call this function while user has changed text in Gridview Textbox.

Here is my Javascript Function’s Decalration:
function processRequest(sender,columnName,ID)
{
var Values = sender.id+”/@,@,@/”+sender.value+”/@,@,@/”+columnName+”/@,@,@/”+Qid;

alert(Values);
}

now to call this function i have added ‘onchange’ event of the Textbox like this:

ProcessRequest

Thats it!!!!

Note : i have known the ASCII character for the Single Quote from HERE


Search Text in Database’s Objects

July 14, 2009

Here is the SQL Stored Procedure which will list all the database’s Objects(SP, Views, Functions etc…) in which the Searched Text exist.

CREATE PROCEDURE [dbo].[SearchTextInDatabase]
@SearchText VARCHAR(200)
AS
BEGIN
— SET NOCOUNT ON added to prevent extra result sets from
— interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @SQL VARCHAR(MAX)

SET @SQL = ‘SELECT Name FROM SysObjects WHERE ID IN
(SELECT ID FROM SysComments WHERE Text Like ”%’ +   @SearchText + ‘%”)
ORDER By Name’

EXEC(@SQL)
END

/*
Here is the Example How to use it….. 🙂

EXEC [SearchTextInDatabase] ‘SearchText’

*/