Wednesday, February 8, 2012

how to Passing a server side variable into javascript

Recently I have seen a server side code which is used to pass the server side value to javascript.So whenever we will transfer the server side value to Javascript we don't need to write server side .For this here i will show a simple way to pass the variable to javascript from server side
<input id="hidCtrl" type="hidden"  runat="server" value='<%# ServerVaribaleValue %>'/>
Here the server side value which is"ServerVaribaleValue" is assigned as a hidden field value.The below javascript will get the value of hidden field
<script language="javascript">
function onclick(){
alert(document.getElementById('hidctrl').value);
}
</script>

2 comments:

Whw&Ggw said...

From security point of view, is it good to use hidden variables at client side?

Bhaskara said...

Thanks a lot for your valuable comment.
HTML hidden field which is simply an input of type hidden. This has no visible rendering although it is in the html. It also has no viewstate properties. So it is not "more" secure than viewstate.

The .Net hidden field does has viewstate storage, but it also causes a regular hidden field to be generated in the html.

The .net hiddenfield will cause data to be placed in viewstate. The HTML ones do not. If you set Visible=False on a .Net control then it is not rendered to the client however it's data is typically stored in viewstate

If we want to encrypt the hiddenfield value we can do it at codebehind like this

Encrypt_Decrypt.Enc_Dec enc = new Encrypt_Decrypt.Enc_Dec();

hdnField1.value = enc.Encrypt(hdnField1.value);

Bel