client server hell :) RegisterStartupScript || RegisterClientScriptBlock && some tips

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.

Advertisements

3 responses to “client server hell :) RegisterStartupScript || RegisterClientScriptBlock && some tips

  1. I was searching for this kind of a blog for months now. Actually lost the hope of finding one, but here i am 🙂 Thanks for the great articles! Looking forward for a little read after dinner 🙂

  2. thanks 🙂 hope u find good info here.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s