Mallika
In asp.net,how to use both code behind code and java script to the same control?
By Mallika in ASP.NET on Aug 20 2010
  • Mallika
    Sep, 2010 1

    I can use both code behind and java script  for the button control 

    e.g
    Login.aspx file with 2 text box and submit button Using java script to validate user name/pass word text box as like below:
    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="Login" %>

    <!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">
    <script language = "javascript" >
        function validate() {
            if (document.getElementById("<%=txtUsername.ClientID%>").value == "") {
                alert("User name cannot be blank");
                document.getElementById("<%=txtUsername.ClientID%>").focus();
                return false;
            }
            if (document.getElementById("<%=txtPassword.ClientID%>").value == "") {
                alert("Password cannot be blank");
                document.getElementById("<%=txtPassword.ClientID%>").focus();
                return false;}




                       return true;}

    </script>
        <title></title>
    </head>
    <body>
        <form  runat="server"  id = "LoginAuth" method ="post" >
        <div>
        UserName:
            <asp:TextBox ID="txtUsername" runat="server"></asp:TextBox>
            <br />
           
            Password:
            <asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
        <br />
            <asp:Button ID="cmdButton" runat="server" Text="Submit"
                onclick="cmdButton_Click" />
       
        </div>
        <asp:Label ID="lblMsg" runat="server" ></asp:Label>
        </form>
    </body>
    </html>


    Login.aspx.cs
    code behind file  can have following code: to connect to db and add javascript function to the button control.

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

    using System.Data;
    using System.Data.SqlClient;
    using System.Configuration;//Configuration Manager
    using System.Web.Security; //for FormAuthentication

    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            cmdButton.Attributes.Add("onclick", "return validate()");

        }
        protected void cmdButton_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                if (dbconn(txtUsername.Text.Trim(), txtPassword.Text.Trim())== true )
                {
                    FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, false  );
                }
                else
                {
                    lblMsg.Text = "Invalid UserName and Password€";


                }
            }
        }
        public  bool dbconn(string u, string p)
        {
           
            SqlConnection conn = new SqlConnection();
            conn.ConnectionString = ConfigurationManager.ConnectionStrings["NWConn"].ConnectionString;
            conn.Open();
            SqlCommand cmd = new SqlCommand("sp_ValidateUser", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlParameter userParam, passwordparam, retValueparam;


            userParam = cmd.Parameters.Add("@UserName", SqlDbType.VarChar, 50) ;
            passwordparam=cmd.Parameters.Add("QPassWord", SqlDbType.VarChar, 50);
            retValueparam= cmd.Parameters.Add("@RetValue", SqlDbType.Int);

            userParam.Direction = ParameterDirection.Input;
            passwordparam.Direction = ParameterDirection.Input;
            retValueparam.Direction = ParameterDirection.ReturnValue ;

            userParam.Value = txtUsername.Text.ToString();
            passwordparam.Value = txtPassword.Text.ToString();
            //try
            //{
          
                if (conn.State == ConnectionState.Closed)
                {
                    conn.Open();
                    cmd.ExecuteNonQuery();

                }
                //Obtain the return value of the stored procedure into a variable
                int retValue = (int)retValueparam.Value;
                if (retValue < 1)
                {
                    return false ;

                }
                else
                {

                    //Return true to indicate that the login is successful
                    return true;
                }

              
            //}
              
            //catch (Exception ex)
            //{
               
            //    lblMsg.Text = ex.Message + "Error connecting to DB";

            //}


            //return false;
          
        }

    }


    • 0
  • Hetalkumar Kachhadiya
    Sep, 2010 1

    Please use the following method for using both the code behing and java script in the same control:

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

    <!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 btnClick() {

    alert("Hello Hetalkumar!! How are you");

    }

    </script>

    <script runat="server">

    protected void Button1_Click(object sender, EventArgs e)

    {

    Response.Write("I am fine");

    }

    </script>

    </head>

    <body>

    <form id="form1" runat="server">

    <div>

    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" OnClientClick="btnClick();" />

    </div>

    </form>

    </body>

    </html>

    You have to define two separate code blocks for writing server side and client side code. And also need to associate the sever events to the server side methods/events and client events to the client side method/functions.

    • 0
  • Purushottam Rathore
    Aug, 2010 27

    Hi Mallika

    You can use code behind nad JavaScript on a same page like as follows:

    Example:

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" ValidateRequest="false" %>
    <!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 runat="server">
    void btnSubmit_Click(Object sender, EventArgs e)
    {
          Response.Write(txtString.Text);
    }
    </script>
    </
    head>
       <
    body>
          <form id="form1" runat="server">
              <asp:TextBox ID="txtString" runat="server" Text="<script>alert('Hello ! Puru');</script>" />
              <asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Submit" />
          </form>
       </
    body>
    </
    html>

    • 0


Most Popular Job Functions


MOST LIKED QUESTIONS