Monday, September 1, 2008

Calling a server side from client's Javascript

Did you ever need something like calling a server side thing from client's? Javascript ... ?

I think this is an easy way of doing that:





Response.Write ( " < script language="javascript"> function SetPmoR_Id() { document.all('" + lkbPmoRepAdd.ClientID + "').click(); } < / script>")

//or:

ClientScript.RegisterClientScriptBlock(this.GetType(), "somethn", " < script type='text/javascript'> function whatdoyouwannacalit() { try {document.all('" + yourlinkbutton.ClientID + "').click();} catch(e){} } < / script>");






what do you think?

you think there's an easier way? comment!

2 comments:

Anonymous said...

There is a better way, in .net you have Page.ClientScript.GetPostBackEventReference(lnkYourLinkNameHere, "Click");

Now this line returns a string that is the well known "__doPostBack(....)" string that is called on a click on a link, button or whatever. The GetPostBackEventReference method has two parameters, one being the control that you want the event generated for and the second seems to be the argument... I am not sure if that isn't by any chance the CommandArgument but I found out it works great. Also check teh related functions from ClientScript, some of them do an asynch call and that is also cool.

Anonymous said...

P.S. You can use that string in a javascript to call the function directly instead of button.click();

e.g. function clickMyButton()
{
<%=Page.ClientScript.
GetPostBackEventReference(
lnkYourLinkNameHere, "Click")%>;
}

which would be rendered as
function clickMyButton()
{
__doPostBack(...);//clicks your button
}