live wid knowledge :)

client server hell

It is always been a tension for web developers to write/read/run/access code between client side and server side. like write script at server

side and use that @ client side or vice versa. today i would like to share some of my knowledge about this. HTH :)

write javascript script @ server side and invoking from server side.

private void Page_Load(object sender, System.EventArgs e)
{
string jsCode= “<script>function myFunc(){ alert(’hello adnan’); }</script>”;
Page.RegisterStartupScript(”adnan”,myfunc);
Button1.Attributes.Add(”onclick”,”return myfunc()”)
}

You can also utilize this method @ client side means write javascript(js) code at serverside and use that by html/javascript (client side)

<html><body>
<a href=”#” onclick=”myFunc()”>hehehe</a>
</body></html>

Writing js script in html/javascript and calling it from server side

<html>
<script>
function myFunc()
{
alert(’hello adnan’);
}
</script>
<body></body></html>

private void Page_Load(object sender, System.EventArgs e)
{
Button1.Attributes.Add(”onclick”,”return myFunc()”);
}
in above case you would need to call it on event (button click) but what if you wanna execute whilst executing server side code
then use RegisterClientScriptBlock

private void Page_Load(object sender, System.EventArgs e)
{
Page.RegisterClientScriptBlock(”adnan”,”myFunc”);
}

to call/access methods of server side you would need to use ajax (xmlhttprequest obj) or callback methodology for async communication and read my blog about ajax and callback here. but u can run statement/instructions of server side code or access objects of server side from client side easily by using :

if u have to run statement e.g, create/assign session in javascript

<% Session.Add(”key”, “value”); %>

or if you wanna use server side obj e.g session object again

alert(’<%= Session[”key”] %>’);

to discuss more scenarios, kindly post comment.

 

Comments

Roman Nikitin said:

Hi, Muhammad!

Nice post.

But Page.RegisterClientScriptBlock is obsolete in Asp.Net 2.0.

You need to use Page.ClientScript.RegisterClientScriptBlock(...).

Check MSDN.

Thanks, Roman.

# January 26, 2008 4:02 AM

Muhammad Adnan Amanullah said:

hello Roman,

i know i didn't use that myself to just to keep my code compatible for those who are still using or have their application in .net 1.1.

anyhow thanks for the comment :)

# January 26, 2008 7:25 AM

Marlon said:

Hi, Just read your post and it is very similar to what I should do, only problem is I'm using VB.net.  Would you happen to know how to do this in VB.Net? Since there is no "RegisterClientScriptBlock" in the intellisence.

# November 3, 2008 4:29 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)