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.