Click here to Skip to main content
15,867,308 members
Articles / Web Development / ASP.NET

Use & Call RegisterStartUpScript, RegisterClientScript and Client-Side Script

Rate me:
Please Sign up or sign in to vote.
4.67/5 (35 votes)
5 Mar 2009CPOL1 min read 479.3K   3.6K   73   21
This article helps a learner to know more about the different ways of calling client side JavaScript from server side code-behind.

Introduction

One can find this article useful during the development phase of a web application. One requires functionalities such as calling JavaScript client side code for validation, confirming popup, prompting user for unwanted action, etc. at server side code behind.

Implementation

Image 1

So we start with an example through code.

RegisterStartupScript

Using RegisterStartupScript we can write a JavaScript function in code behind and call it from code-behind or from HTML. Look at the code below for reference.

Calling & Writing JavaScript Function from Server Side Code Behind

C#
private void Page_Load(object sender, System.EventArgs e)
{
    string jScriptValidator;
    jScriptValidator="<script> function ReqFieldValidator()" + 
                " { if (document.forms[0].txtField.value == '') \n"; 
    jScriptValidator+="{ alert('TextBox cannot be empty') \n ";
    jScriptValidator+="return false; \n";
    jScriptValidator+="} \n";
    jScriptValidator+=" return true \n";
    jScriptValidator+=" } </script>";
    Page.RegisterStartupScript("regJSval",jScriptValidator);
    btnSubmit.Attributes.Add("onclick","return ReqFieldValidator()");
}

Writing JavaScript Function in Server Side Code Behind and Calling from HTML

C#
//Server side

private void Page_Load(object sender, System.EventArgs e)
{
    string jScript;
    jScript="<script>function JavScriptFn(){alert" + 
      " ('Client Function in javascript is call')}</script>";
}
HTML
//HTML side
< A onclick="JavScriptFn()" >
< asp:Label id="Label1" runat="server" Width="281px" 
   ForeColor="#8080FF">Click to call Javascript function.
</asp:Label> >/A >

Writing JavaScript in HTML and Calling it from Code-behind

JavaScript
<Head >
    <script>

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

    </script>
</Head >
C#
private void Page_Load(object sender, System.EventArgs e)
{
    btnOK.Attributes.Add("onclick","return ReqField1Validator()");
}

RegisterClientScriptBlock

Suppose we want JavaScript code to be executed but not a function. In that case, we make use of RegisterClientScriptBlock.RegisterClientScriptBlock which helps to make server side code as well as client side code inline to each other.

C#
private void btnClientBlock_Click(object sender, System.EventArgs e)
{
    string jScript;
    jScript="<script>alert ('Javascript block of code executed')</script>";
    Page.RegisterClientScriptBlock("keyClientBlock",jScript);
    lblSequencial.Text="Remaining part of the code executed";
}

ASP.NET 2.0 RegisterClientScriptBlock/RegisterStartupScript

One can call JavaScript client side function directly from code behind using RegisterStartupScript. If one wants JavaScript to be embedded into codebehind, then make use of RegisterClientScriptBlock:

JavaScript
<script>
function fnShowMessage()
{
    alert(" Invoke Javascript function from Server Side Code Behind ");
}
</script>
C#
protected void Button1_Click(object sender, EventArgs e)
    {
        ClientScript.RegisterStartupScript
		(GetType(),"Javascript", "javascript: fnShowMessage(); ",true);
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        ClientScript.RegisterClientScriptBlock(GetType(), "Javascript", 
		"<script>alert('Record Added Successfully')</script>");
    }

Hope you find the above article helpful. Any suggestions are most welcome.

History

  • 25th July, 2005: Initial post
  • 4th March, 2009: Article updated

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
Australia Australia
Whatsup-->Exploring--> MVC/HTML5/Javascript & Virtualization.......!
www.santoshpoojari.blogspot.com

Comments and Discussions

 
QuestionSolution Pin
Alireza_136228-Mar-13 16:19
Alireza_136228-Mar-13 16:19 
GeneralMy vote of 5 Pin
Iris Star22-Aug-12 21:31
Iris Star22-Aug-12 21:31 
GeneralMy vote of 5 Pin
P.Salini22-Jun-12 1:17
P.Salini22-Jun-12 1:17 
GeneralMy vote of 5 Pin
Anuj Banka10-Oct-11 3:23
Anuj Banka10-Oct-11 3:23 
QuestionRegistring Client Script in ASP.NET Pin
awadhendra tiwari27-Aug-11 2:35
awadhendra tiwari27-Aug-11 2:35 
QuestionUse of 'calling' is misleading [modified] Pin
Gebbetje24-Jun-10 0:42
Gebbetje24-Jun-10 0:42 
The use of the word 'calling' in for example "Calling & Writing JavaScript Function from Server Side Code Behind" suggests that you can call/activate a javascript function from code behind. Following one of your suggestions doesn't have this result. It only registers the javascript function that's only being called by actions on the part of the user.

(When I select an option button from code behind the javascript function that's attached to the option button isn't being called. Not automatically, not through using RegisterStartupScript.)

Please correct me if I'm wrong.


Edit:
This post http://forums.asp.net/p/982967/3943137.aspx#3943137
solved (large part of) my problem.

modified on Thursday, June 24, 2010 10:24 AM

AnswerRe: Use of 'calling' is misleading [modified] Pin
Fandango6829-Mar-17 16:46
Fandango6829-Mar-17 16:46 
GeneralMy vote of 1 Pin
Miguel J23-Mar-10 14:18
Miguel J23-Mar-10 14:18 
GeneralRe: My vote of 1 Pin
Valery Possoz4-Jan-12 4:52
professionalValery Possoz4-Jan-12 4:52 
Generalvery helpful !! Pin
Libin Chen28-Jun-07 15:10
Libin Chen28-Jun-07 15:10 
GeneralRe: very helpful !! Pin
fletchsod13-Oct-08 4:53
fletchsod13-Oct-08 4:53 
GeneralRegistering a ClientScriptBlock from a code module or dll Pin
tony_trotter3-Apr-06 11:23
tony_trotter3-Apr-06 11:23 
Questioncan i do the inverse Pin
marcoscavaleiro28-Nov-05 11:11
marcoscavaleiro28-Nov-05 11:11 
AnswerRe: can i do the inverse Pin
azam's14-Feb-07 21:01
azam's14-Feb-07 21:01 
GeneralJavascript files Pin
dudamir25-Jul-05 7:04
dudamir25-Jul-05 7:04 
GeneralRe: Javascript files Pin
santosh poojari25-Jul-05 19:07
santosh poojari25-Jul-05 19:07 
GeneralRe: Javascript files Pin
aprenot27-Jul-05 9:57
aprenot27-Jul-05 9:57 
GeneralRe: Javascript files Pin
santosh poojari28-Jul-05 19:45
santosh poojari28-Jul-05 19:45 
GeneralRe: Javascript files Pin
freesmile11-Sep-08 4:17
freesmile11-Sep-08 4:17 
GeneralRe: Javascript files Pin
oguzhan.kahyaoglu22-Mar-12 22:53
oguzhan.kahyaoglu22-Mar-12 22:53 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.