29 Aralık 2016 Perşembe

Writing javascript in *.cs file

There are two "Asp.NET methods" for writing script blocks in the server side.

1) RegisterStartupScript
2) RegisterClientScriptBlock

If RegisterStartupScript method is used,  the script element is written just before closing the form element. 
This means that every html controls have been defined before the script block. Therefore the script objects can point these reference without any problem. 

When RegisterClientScriptBlock method is used, the script block is written before the definitions of the html objects in an aspx file. Therefore the statements in the scripts should be written in a function that can be called just after the html objects are created. 

Let's make it clear with an example.

Think we have a Label control(Label1) and we want it to show the client date.

When we use RegisterClientScriptBlock like the figure below, Label1 does not show us the date. 


Infact while the page is loading, an error is occured. The error can be seen by opening developer tools of Chrome.  The error is : "Uncaught TypeError: Cannot set property 'innerHTML' of null" which means it is not possible to set the property of a control which hasn't been created yet. Labl1 has not been created yet.


If you press the error link it will show you the code that can not be run properly.

Let's write the same script by using RegisterStartupScript.


Label1's innerHTML can be assigned by the date function.
Because the script block is written after HTML controls are defined.




Hiç yorum yok:

Yorum Gönder