This is a migrated thread and some comments may be shown as answers.

[Solved] Call JavaScript from server side

3 Answers 616 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
Robert
Top achievements
Rank 1
Robert asked on 24 May 2013, 12:51 AM
Hi,

Is it possible to execute a Javascript from server side? Seems foolish, I know one is client side and other is server side. Still I have a requirement to invoke a JavaScript based on some condition on a radbutton click?

Thanks for replying,
Robert.

3 Answers, 1 is accepted

Sort by
0
Shinu
Top achievements
Rank 2
answered on 24 May 2013, 02:43 AM
Hi Robert,

It is possible to execute a JavaScript from server-side code. In order to do this, make sure that the code is actually inserted on the page – the easiest way is to put a simple alert() and check if it is fired. Also the controls are rendered on the page before referencing them in your JavaScript function. Please have a look at the following sample code.

C#:
protected void RadButton1_Click(object sender, EventArgs e)
{
    string scriptstring = "alert('JavaScript Executed');";
    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "JavaScript", scriptstring, true);
}

Thanks,
Shinu.
0
Robert
Top achievements
Rank 1
answered on 27 May 2013, 11:32 AM
Hi shinu, my js is defined in aspx. So how to call from there?
0
Shinu
Top achievements
Rank 2
answered on 27 May 2013, 11:51 AM
Hi Robert,

Please have a look at the following code I tried which works fine at my end. For the JavaScript to work properly, it should be placed inside the html body as follows.

ASPX:
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function myJavaScript() {
            alert("JavaScript Executed");
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <div>
        <telerik:RadButton ID="RadButton1" runat="server" Text="Click" OnClick="RadButton1_Click">
        </telerik:RadButton>
        <asp:Label ID="Label1" runat="server"></asp:Label>
    </div>
    </form>
</body>

C#:
protected void RadButton1_Click(object sender, EventArgs e)
{
    Label1.Text = "<script type='text/javascript'>myJavaScript()</script>";
}

Thanks,
Shinu.
Tags
General Discussions
Asked by
Robert
Top achievements
Rank 1
Answers by
Shinu
Top achievements
Rank 2
Robert
Top achievements
Rank 1
Share this question
or