RegisterClientScriptBlock and RegisterStartupScript functions in ajax c#

An example for RegisterClientScriptBlock and RegisterStartupScript is explained below.

Differences between RegisterClientScriptBlock & RegisterStartupScript

They both are used for same purpose but the differences between them are mentioned below.

1) The method RegisterStartupScript adds Javascript to the web form right before the ending ‘form’ tag whereas the method RegisterClientScriptBlock adds Javascript to the web form, right after the starting ‘form’ tag .

2) The method RegisterStartupScript is used when you want to assign any value or property or want to get the value or property from any element whereas in case of the method RegisterClientScriptBlock we will get an error as ‘object undefined’.

3) The method RegisterStartupScript holds the code which will run as soon as the browser parses it but the method RegisterClientScriptBlock holds routines and libraries that the whole page uses.

Aspx Code

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>RegisterClientScriptBlock and RegisterStartupScript functions in ajax c#</title>

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#btnGetResponse").click(function () {
                $.ajax({
                    type: "POST",
                    url: "Default.aspx/GetResponse",
                    data: '{}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        if (response.d == true) {
                            alert("You will now be redirected.");
                            window.location = "http://easycode.onewebapp.com/";
                        }
                    },
                    failure: function (response) {
                        alert(response.d);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <h3>RegisterClientScriptBlock and RegisterStartupScript functions in ajax c#</h3>
            <input id="btnGetResponse" type="button" value="Redirect" />
        </div>
    </form>
</body>
</html>

 

Cs Code

[System.Web.Services.WebMethod]
       public static bool GetResponse()
       {
           return true;
       }

 

Output of RegisterClientScriptBlock and RegisterStartupScript

 

Demo Code

Download Demo