Articles → .NET → Call Javascript From Code Behind In Asp.Net

Call Javascript From Code Behind In Asp.Net






Software Requirement





Prerequisite Knowledge




  1. How to create a project using visual studio?
  2. Basic knowledge about basic controls like button etc and their events.

Steps Of Execution




  1. Create a new project
  2. Add controls to the page
  3. Add JavaScript code in code behind



Create A New Project




Picture showing the project structure of asp.net
Click to Enlarge


Add Controls To The Page




Picture showing the web page with the button control
Click to Enlarge


Add Javascript Code In Code Behind




using System;

public partial class _Default: System.Web.UI.Page {
	protected void Page_Load(object sender, EventArgs e) {

}
	protected void Button1_Click(object sender, EventArgs e) {
		this.ClientScript.RegisterStartupScript(this.GetType(), "ALERTMESSAGE", "alert('Button clicked')", true);
	}
}




  1. Type – Type of start up script to register
  2. Key – This is the key of the script to register
  3. Script – JavaScript which you want to register.
  4. AddScripttags – It is a Boolean value (when set to true) ensures that script is added between the script tags.

Output


Picture showing the alert message when user clicks on the button
Click to Enlarge



Picture showing the rendered script in view code
Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Thursday, May 2, 2013

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250