Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of RegisterClientScriptBlock/RegisterStartupScript in asp.net 3.5

I'm not able to understand what is the use of it.RegisterClientScriptBlock/RegisterStartupScript.

When we can directly write the JavaScript code in.js file then call it on the button

ex: 2

<script>
    function ReqField1Validator() { 
        if (document.forms[0].txtField1.value == '') {
            alert('TextBox cannot be empty') 
            return false
         } 
         return true 
     } 
</script>

btnPostback.Attributes.Add("onclick","return ReqField1Validator()");

What will be the use of RegisterClientScriptBlock/RegisterStartupScript?

protected void btnPostback_Click(object sender, EventArgs e)  {
    System.Text.StringBuilder sb = new System.Text.StringBuilder();
    sb.Append(@"<script language='javascript'>");
    sb.Append(@"var lbl = document.getElementById('lblDisplayDate');");
    sb.Append(@"lbl.style.color='red';");
    sb.Append(@"</script>");

    if (!ClientScript.IsStartupScriptRegistered("JSScript")){
        ClientScript.RegisterStartupScript(this.GetType(), "JSScript", sb.ToString());
    }
}

Read few articles but they were not clear.

Any thoughts on this would be great.

like image 909
Kumee Avatar asked Aug 05 '11 04:08

Kumee


1 Answers

RegisterStartupScript is used to register and execute javascript functions once the page finished loading, this javascript code executes before the onLoad event of page is raised. You can use it for multiple reasons, for example, you want to execute any particular javascript function depending on some variable value in your code behind.

On the other hand, RegisterClientScriptBlock is used to add a script block on the top of your page, similarly it provides you a way to work with both client side code and server code in your code behind.

like image 126
Waqas Avatar answered Oct 07 '22 21:10

Waqas