Calling a javascript function from C# code behind

Sometimes we want to call javascript function from C# code behind, because some time visual studio doesn't show you all events that normally your control should have for calling javascript functions, so to get rid of this problem we call our javascript function from code behind, in this example i am using C# code behind to fire the event and call the javascript function.

Yourpage.aspx

Let's consider this is the javascript function in your aspx page that you want to call from C# code behind.

<script language="javascript">
function alertfunc()
{
alert("This is the way to call the javascript function from C# code behind");
}

<script>


And now for instance this is the dropdownlist in your aspx page and you will call the javascript function by firing its onChange event.

<asp:DropDownList ID="ddl_SearchOption" runat="server" >

<asp:ListItem Text="Muhammad Ali" Value="1"></asp:ListItem>
<asp:ListItem Text="Adeel Fakhar" Value="2"></asp:ListItem>
</asp:DropDownList>

Yourpage.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
ddl_SearchOption.Attributes.Add("onChange", "alertfunc()");
}

 
Note:- If you want to write and execute the javascript function from code behind then please refer to this tutorial Learn how to write and execute the javascript code from c# code behind
So this is the way to call the javascript function from C#

0 comments: