Friday 6 December 2013

Call JavaScript Function from CodeBehind in asp.net

Output:


Aspx page

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    
  <script language="javascript" type="text/javascript">
      function Confirm() {
          document.getElementById('<%=Panel1.ClientID %>').style.background = "Teal";
          var checkUpdate = confirm("Do you wish to save changes?");
          if (checkUpdate) {
              return true;
          }
          else {
              return false;
          }
      }
    </script>
    <style>
    .col
    {
        background-color:Red;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        <asp:Button ID="Button1" runat="server" Text="Button"
            onclick="Button1_Click1" />
        <asp:Panel ID="Panel1" CssClass="col" Width="100px" Height="100px" runat="server">
        </asp:Panel>
    </div>
    </form>
</body>
</html>


Aspx.cs page

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default3 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
       
    }
  
    protected void Button1_Click1(object sender, EventArgs e)
    {
        if (true)
        {
            string script = "<SCRIPT LANGUAGE='JavaScript'> ";
            script += "Confirm()";
            script += "</SCRIPT>";
            Page.RegisterStartupScript("ClientScript", script);

            //If Javascript Ok Call Update,Otherewise,nothing; 
        }
    }
    
}

No comments:

Post a Comment