We help IT Professionals succeed at work.

Lookup user against two values

asp_net2
asp_net2 asked
on
Hello Experts,

I have the following code below. I need to compare two values in my database against the values entered in two TextBox controls and if they exist send an email to the email address listed in DB and if they don't exist display error message. Please see my attached code and stored procedure.


protected void btn_ForgotPassword_Click(object sender, EventArgs e)
    {
        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["HealthCourses"].ConnectionString))
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "HealthCourses_VerifyUsernameEmail";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = conn;

            cmd.Parameters.Add("@users_username", SqlDbType.VarChar, 50).Value = txtUsername.Text;
            cmd.Parameters.Add("@users_email", SqlDbType.VarChar, 100).Value = txtEmail.Text;

            try
            {
                conn.Open();

                SqlDataReader rdr = cmd.ExecuteReader();

                if (rdr.Read())
                {
                    Session["UsersID"] = rdr["users_id"].ToString();
                    SendForgotPasswordEmail();
                }
                else
                {
                    lblForgotPasswordError.Text = "Invalid Credentials";
                }

                Response.Redirect("forgotpassword_success.aspx");
            }

            catch (Exception ex)
            {
                lblForgotPasswordError.Text = ex.Message.ToString();
            }
        }
    }

Open in new window

CREATE PROCEDURE HealthCourses_VerifyUsernameEmail

(
@users_username varchar(50),
@users_email varchar(100)
)

AS 

SELECT users_id, users_username, users_email
FROM dbo.HealthCourses_Users
WHERE users_username = @users_username AND users_email = @users_email

Open in new window

Comment
Watch Question

Commented:
I think your syntax for the
parameter.add

Open in new window

is wrong. MSDN styates 2 ways:
       ' Add Parameter and next assign the value
        command.Parameters.Add("@ID", SqlDbType.Int)
        command.Parameters("@ID").Value = customerID

        ' Add parameter and value in one statement
        command.Parameters.AddWithValue("@ID", customerID)

Open in new window

Choose the one that fits you best

Author

Commented:
Ambusy,

That has nothing to do with what I'm asking help for!
Full Stack .NET Developer
Commented:
Hello asp_net2, I have seen your code, the only thing that I think is in a wrong place is the Response.Redirect, try this:
protected void btn_ForgotPassword_Click(object sender, EventArgs e)
    {
        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["HealthCourses"].ConnectionString))
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "HealthCourses_VerifyUsernameEmail";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = conn;

            cmd.Parameters.Add("@users_username", SqlDbType.VarChar, 50).Value = txtUsername.Text;
            cmd.Parameters.Add("@users_email", SqlDbType.VarChar, 100).Value = txtEmail.Text;

            try
            {
                conn.Open();

                SqlDataReader rdr = cmd.ExecuteReader();

                if (rdr.Read())
                {
                    Session["UsersID"] = rdr["users_id"].ToString();
                    SendForgotPasswordEmail();
                    Response.Redirect("forgotpassword_success.aspx");
                }
                else
                {
                    lblForgotPasswordError.Text = "Invalid Credentials";
                }
            }

            catch (Exception ex)
            {
                lblForgotPasswordError.Text = ex.Message.ToString();
            }
        }
    }

Open in new window


Or you need the code for your SendForgotPasswordEmail method?

Author

Commented:
Hi yv989c,

Thank you! After I made that post I came up with the following code below which I think may be overkill but was getting despeartate for help :)


However your solution in 37074541 works exactly as I needed :) But was wondering if this was a better way or just more overkill .
protected void btn_ForgotPassword_Click(object sender, EventArgs e)
    {
        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["HealthCourses"].ConnectionString))
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "HealthCourses_VerifyUsernameEmail";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = conn;

            cmd.Parameters.Add("@users_username", SqlDbType.VarChar, 50).Value = txtUsername.Text;
            cmd.Parameters.Add("@users_email", SqlDbType.VarChar, 100).Value = txtEmail.Text;

            try
            {
                conn.Open();

                SqlDataReader rdr = cmd.ExecuteReader();

                if (rdr.Read())
                {
                    if (txtUsername.Text == rdr["users_username"].ToString() && txtEmail.Text == rdr["users_email"].ToString())
                    {
                        hf_users_id.Value = rdr["users_id"].ToString();
                        SendForgotPasswordEmail();
                        Response.Redirect("forgotpassword_success.aspx");
                    }
                    else
                    {
                        lblForgotPasswordError.Text = "Invalid Credentials Supplied";
                    }
                }
            }

            catch (Exception ex)
            {
                lblForgotPasswordError.Text = ex.Message.ToString();
            }
        }
    }

Open in new window

Author

Commented:
Hi yv989c,

I would like to close this post. But I have a small question before I do. I ran into an issue if a user would happen to keep clicking the "Submit Button" more than once. When he/she hits the button more than once it sends that many emails out rather than just one email. Is there a way to stop that? Please see my updated code. Also, I was using jQuery to prevent that but for some reason it's not stopping
protected void btn_ForgotPassword_Click(object sender, EventArgs e)
    {
        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["HealthCourses"].ConnectionString))
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "HealthCourses_VerifyUsernameEmail";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = conn;

            cmd.Parameters.Add("@users_username", SqlDbType.VarChar, 50).Value = txtUsername.Text;
            cmd.Parameters.Add("@users_email", SqlDbType.VarChar, 100).Value = txtEmail.Text;

            try
            {
                conn.Open();

                SqlDataReader rdr = cmd.ExecuteReader();

                if (rdr.Read())
                {
                    hf_users_id.Value = rdr["users_id"].ToString();
                    SendForgotPasswordEmail();
                    Response.Redirect("forgotpassword_success.aspx");
                }
                else
                {

                    lblForgotPasswordError.Text = "We are unable to locate your account";
                }
            }

            catch (Exception ex)
            {
                lblForgotPasswordError.Text = ex.Message.ToString();
            }
        }
    }

Open in new window

Carlos VillegasFull Stack .NET Developer

Commented:
Hello, to give you a way to handle this I need to know if you are using Validator controls in that page, like RequiredFieldValidator etc.., are you?

Author

Commented:
Yes, I have attached the Markup as well. I also attached the <head> and begining <body> section to show you how I tried to use jQuery to prevent multiple clicks.


HEAD SECTION:

<head runat="server">
    <title>Forgot your Password</title>
    <link href="../../css/main.css" rel="stylesheet" type="text/css" />
    <script src="../../Scripts/jquery-1.5.js" type="text/javascript"></script>
</head>

Open in new window

BEGINNING BODY:

<script type="text/javascript">
    $('#form1').submit(function () { $('btn_ForgotPassword.ClientID[type=submit]', this).attr('disabled', 'disabled'); });
</script>

Open in new window

HTML MARKUP:

            <div id="primary">
                <h1>FORGOT YOUR PASSWORD</h1>
                <p>Please enter your Username and Email Address below to help identify your account. You will then receive an email with instructions on how to reset your password.</p>
                <asp:Label ID="lblUsername" runat="server" CssClass="CourseDescTitle" Text="Username"></asp:Label>&nbsp;&nbsp;<asp:RequiredFieldValidator ID="rfv_Username" runat="server" ControlToValidate="txtUsername" CssClass="required" ErrorMessage="Required"></asp:RequiredFieldValidator>
                <br />
                <asp:TextBox ID="txtUsername" CssClass="txtCourseInsert" runat="server" Width="300" MaxLength="50"></asp:TextBox>
                <br />
                <br />
                <asp:Label ID="lblEmail" CssClass="CourseDescTitle" runat="server" Text="Email"></asp:Label>&nbsp;&nbsp;<asp:RequiredFieldValidator ID="rfv_Email" runat="server" CssClass="required" ControlToValidate="txtEmail" ErrorMessage="Required"></asp:RequiredFieldValidator>
                <br />
                <asp:TextBox ID="txtEmail" CssClass="txtCourseInsert" Width="300" MaxLength="50" runat="server"></asp:TextBox>
                <br />
                <asp:HiddenField ID="hf_users_id" runat="server" />
                <br />
                <asp:Label ID="lblForgotPasswordError" CssClass="required" runat="server"></asp:Label>
                <br />
                <br />
                <asp:Button ID="btn_ForgotPassword" runat="server" Text="Search" onclick="btn_ForgotPassword_Click" />
            </div>

Open in new window

Carlos VillegasFull Stack .NET Developer

Commented:
Ok, please open that page in your web browser, then right click on it and look for an option that display the page source, then copy all the html and paste it here inside a code block.

Author

Commented:
Wow, never saw that format before. Interesting!!! Why does it format it differenlty than how I program it?


<!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><title>
	Wellness Choice Program - Forgot your Password
</title><link href="../../css/main.css" rel="stylesheet" type="text/css" />
    <script src="../../Scripts/jquery-1.5.js" type="text/javascript"></script>
</head>
<body class="info">
 
<script type="text/javascript"> 
    $('#form1').submit(function () { $('btn_ForgotPassword.ClientID[type=submit]', this).attr('disabled', 'disabled'); });
</script>
 
<form method="post" action="forgotpassword.aspx" onsubmit="javascript:return WebForm_OnSubmit();" id="form1">
<div class="aspNetHidden">
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKLTQ1MzI0NzE4NmRknwXBoFOx9UY6wxS8xA0c6JNPGfqYL1+Xptk9UfhAh0k=" />
</div>
 
<script type="text/javascript"> 
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
    theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;
        theForm.submit();
    }
}
//]]>
</script>
 
 
<script src="/WellnessSite/WebResource.axd?d=DOmt6ALb9vHY_AG_9IH-ox4RXADkc7bYSpTbesEwG5UI28rq-epVbzxWDu-lnIFlh5-HgORdiV8Dq0-3_uQqJXTWc7kMv43hdHKkhVYSpNs1&amp;t=634541131847043842" type="text/javascript"></script>
 
 
<script src="/WellnessSite/WebResource.axd?d=NjQMHSWr_48yq9jxU85S_mwdeITJUu-k8M2PtXpCsGJFqGzNUcjIpYjV05y8y4v8SAZvAfyLb71blrOMusA42khAZbNknGvlPzuk9-IPDZo1&amp;t=634541131847043842" type="text/javascript"></script>
<script type="text/javascript"> 
//<![CDATA[
function WebForm_OnSubmit() {
if (typeof(ValidatorOnSubmit) == "function" && ValidatorOnSubmit() == false) return false;
return true;
}
//]]>
</script>
 
<div class="aspNetHidden">
 
	<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWBQKNyNivCwKl1bK4CQKE8/26DALCl5SZDgKI8cNQHk/fRHOI4yB9tbc1njzLy+sZLzbko6hvyLDpoap+YiU=" />
</div>
	<div id="wrapper">
    	<div id="header">
        <img src="../../images/logo.png" alt="Shape Up Logo" />
            <div id="nav">
                <ul>
                    <li><a href="../../index.aspx">HOME</a></li>
                    <li class="current"><a href="../index.aspx">PROGRAM INFORMATION</a></li>
                    <li><a href="http://wellnesstracker.pacyber.org/" target="_blank">REPORTING SYSTEM</a></li>
                    <li><a href="../../contact/index.aspx">CONTACT</a></li>
                </ul>
            </div>
        </div>
        <div id="content">
            <div id="primary">
                <h1>FORGOT YOUR PASSWORD</h1>
                <p>Please enter your Username and Email Address below to help identify your account. You will then receive an email with instructions on how to reset your password.</p>
                <span id="lblUsername" class="CourseDescTitle">Username</span>&nbsp;&nbsp;<span id="rfv_Username" class="required" style="visibility:hidden;">Required</span>
                <br />
                <input name="txtUsername" type="text" maxlength="50" id="txtUsername" class="txtCourseInsert" style="width:300px;" />
                <br />
                <br />
                <span id="lblEmail" class="CourseDescTitle">Email</span>&nbsp;&nbsp;<span id="rfv_Email" class="required" style="visibility:hidden;">Required</span>
                <br />
                <input name="txtEmail" type="text" maxlength="50" id="txtEmail" class="txtCourseInsert" style="width:300px;" />
                <br />
                <input type="hidden" name="hf_users_id" id="hf_users_id" />
                <br />
                <span id="lblForgotPasswordError" class="required"></span>
                <br />
                <br />
                <input type="submit" name="btn_ForgotPassword" value="Search" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;btn_ForgotPassword&quot;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, false))" id="btn_ForgotPassword" />
            </div>
            <div id="secondary">
                <h1>PROGRAMS</h1>
                <ul>
                    <li><a href="../index.aspx">General Health Awareness Program 1</a></li>
                </ul>
            </div>
        </div>
        <div id="footer">
            
        </div>
    </div>
 
<script type="text/javascript"> 
//<![CDATA[
var Page_Validators =  new Array(document.getElementById("rfv_Username"), document.getElementById("rfv_Email"));
//]]>
</script>
 
<script type="text/javascript"> 
//<![CDATA[
var rfv_Username = document.all ? document.all["rfv_Username"] : document.getElementById("rfv_Username");
rfv_Username.controltovalidate = "txtUsername";
rfv_Username.errormessage = "Required";
rfv_Username.evaluationfunction = "RequiredFieldValidatorEvaluateIsValid";
rfv_Username.initialvalue = "";
var rfv_Email = document.all ? document.all["rfv_Email"] : document.getElementById("rfv_Email");
rfv_Email.controltovalidate = "txtEmail";
rfv_Email.errormessage = "Required";
rfv_Email.evaluationfunction = "RequiredFieldValidatorEvaluateIsValid";
rfv_Email.initialvalue = "";
//]]>
</script>
 
 
<script type="text/javascript"> 
//<![CDATA[
 
var Page_ValidationActive = false;
if (typeof(ValidatorOnLoad) == "function") {
    ValidatorOnLoad();
}
 
function ValidatorOnSubmit() {
    if (Page_ValidationActive) {
        return ValidatorCommonOnSubmit();
    }
    else {
        return true;
    }
}
        //]]>
</script>
</form>
</body>
</html>

Open in new window

Carlos VillegasFull Stack .NET Developer

Commented:
In your aspx page, move this:
<script type="text/javascript"> 
    $('#form1').submit(function () { $('btn_ForgotPassword.ClientID[type=submit]', this).attr('disabled', 'disabled'); });
</script>

Open in new window

After your </form> element, must be like:
........
</form>
<script type="text/javascript"> 
    $('#form1').submit(function () { $('btn_ForgotPassword.ClientID[type=submit]', this).attr('disabled', 'disabled'); });
</script>

Open in new window

And see if that fix your problem.

Author

Commented:
No luck, it still submits multiple emails :(

Do you recommend a server side approach rather than clients side?
Carlos VillegasFull Stack .NET Developer

Commented:
no, that must be do on client side, give me a moment to check carefully all the code
Carlos VillegasFull Stack .NET Developer

Commented:
Ok, I think that I got it, try this:

Add this to your code behind file:
protected override void Render(HtmlTextWriter writer)
{
    ClientScript.RegisterOnSubmitStatement(this.GetType(), "DisableButton", "$('#btn_ForgotPassword').attr('disabled', 'disabled')");
    base.Render(writer);
}

Open in new window


And remove this from your aspx page wherever it is:
<script type="text/javascript"> 
    $('#form1').submit(function () { $('btn_ForgotPassword.ClientID[type=submit]', this).attr('disabled', 'disabled'); });
</script>

Open in new window


After that changes, try again.
Carlos VillegasFull Stack .NET Developer

Commented:
Wow, never saw that format before. Interesting!!! Why does it format it differenlty than how I program it?
That is HTML buddy, before start to making web applications I recommend you to learn html first, all the web is based on it.

Author

Commented:
That did not work either :( When I click on the button this time either once or multiple times then I don't receive and email nor do I get redirect to a success page.

>> Wow, never saw that format before. Interesting!!! Why does it format it differenlty than how I program it?

I was referring to how it looks at design time compared to when you run it and see the source code after it runs. Looks different.
Carlos VillegasFull Stack .NET Developer

Commented:
Please sent again your rendered html code

Author

Commented:
rendered html attached.
<!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><title>
	Wellness Choice Program - Forgot your Password
</title><link href="../../css/main.css" rel="stylesheet" type="text/css" />
    <script src="../../Scripts/jquery-1.5.js" type="text/javascript"></script>
</head>
<body class="info">
<form method="post" action="forgotpassword.aspx" onsubmit="javascript:return WebForm_OnSubmit();" id="form1">
<div class="aspNetHidden">
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKLTQ1MzI0NzE4NmRknwXBoFOx9UY6wxS8xA0c6JNPGfqYL1+Xptk9UfhAh0k=" />
</div>
 
<script type="text/javascript"> 
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
    theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;
        theForm.submit();
    }
}
//]]>
</script>
 
 
<script src="/WellnessSite/WebResource.axd?d=DOmt6ALb9vHY_AG_9IH-ox4RXADkc7bYSpTbesEwG5UI28rq-epVbzxWDu-lnIFlh5-HgORdiV8Dq0-3_uQqJXTWc7kMv43hdHKkhVYSpNs1&amp;t=634541131847043842" type="text/javascript"></script>
 
 
<script src="/WellnessSite/WebResource.axd?d=NjQMHSWr_48yq9jxU85S_mwdeITJUu-k8M2PtXpCsGJFqGzNUcjIpYjV05y8y4v8SAZvAfyLb71blrOMusA42khAZbNknGvlPzuk9-IPDZo1&amp;t=634541131847043842" type="text/javascript"></script>
<script type="text/javascript"> 
//<![CDATA[
function WebForm_OnSubmit() {
if (typeof(ValidatorOnSubmit) == "function" && ValidatorOnSubmit() == false) return false;$('#btn_ForgotPassword').attr('disabled', 'disabled');
return true;
}
//]]>
</script>
 
<div class="aspNetHidden">
 
	<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWBQKNyNivCwKl1bK4CQKE8/26DALCl5SZDgKI8cNQHk/fRHOI4yB9tbc1njzLy+sZLzbko6hvyLDpoap+YiU=" />
</div>
	<div id="wrapper">
    	<div id="header">
        <img src="../../images/logo.png" alt="Shape Up Logo" />
            <div id="nav">
                <ul>
                    <li><a href="../../index.aspx">HOME</a></li>
                    <li class="current"><a href="../index.aspx">PROGRAM INFORMATION</a></li>
                    <li><a href="http://wellnesstracker.pacyber.org/" target="_blank">REPORTING SYSTEM</a></li>
                    <li><a href="../../contact/index.aspx">CONTACT</a></li>
                </ul>
            </div>
        </div>
        <div id="content">
            <div id="primary">
                <h1>FORGOT YOUR PASSWORD</h1>
                <p>Please enter your Username and Email Address below to help identify your account. You will then receive an email with instructions on how to reset your password.</p>
                <span id="lblUsername" class="CourseDescTitle">Username</span>&nbsp;&nbsp;<span id="rfv_Username" class="required" style="visibility:hidden;">Required</span>
                <br />
                <input name="txtUsername" type="text" maxlength="50" id="txtUsername" class="txtCourseInsert" style="width:300px;" />
                <br />
                <br />
                <span id="lblEmail" class="CourseDescTitle">Email</span>&nbsp;&nbsp;<span id="rfv_Email" class="required" style="visibility:hidden;">Required</span>
                <br />
                <input name="txtEmail" type="text" maxlength="50" id="txtEmail" class="txtCourseInsert" style="width:300px;" />
                <br />
                <input type="hidden" name="hf_users_id" id="hf_users_id" />
                <br />
                <span id="lblForgotPasswordError" class="required"></span>
                <br />
                <br />
                <input type="submit" name="btn_ForgotPassword" value="Search" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;btn_ForgotPassword&quot;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, false))" id="btn_ForgotPassword" />
            </div>
            <div id="secondary">
                <h1>PROGRAMS</h1>
                <ul>
                    <li><a href="../index.aspx">General Health Awareness Program 1</a></li>
                </ul>
            </div>
        </div>
        <div id="footer">
            
        </div>
    </div>
 
<script type="text/javascript"> 
//<![CDATA[
var Page_Validators =  new Array(document.getElementById("rfv_Username"), document.getElementById("rfv_Email"));
//]]>
</script>
 
<script type="text/javascript"> 
//<![CDATA[
var rfv_Username = document.all ? document.all["rfv_Username"] : document.getElementById("rfv_Username");
rfv_Username.controltovalidate = "txtUsername";
rfv_Username.errormessage = "Required";
rfv_Username.evaluationfunction = "RequiredFieldValidatorEvaluateIsValid";
rfv_Username.initialvalue = "";
var rfv_Email = document.all ? document.all["rfv_Email"] : document.getElementById("rfv_Email");
rfv_Email.controltovalidate = "txtEmail";
rfv_Email.errormessage = "Required";
rfv_Email.evaluationfunction = "RequiredFieldValidatorEvaluateIsValid";
rfv_Email.initialvalue = "";
//]]>
</script>
 
 
<script type="text/javascript"> 
//<![CDATA[
 
var Page_ValidationActive = false;
if (typeof(ValidatorOnLoad) == "function") {
    ValidatorOnLoad();
}
 
function ValidatorOnSubmit() {
    if (Page_ValidationActive) {
        return ValidatorCommonOnSubmit();
    }
    else {
        return true;
    }
}
        //]]>
</script>
</form>
</body>
</html>

Open in new window

Carlos VillegasFull Stack .NET Developer

Commented:
Oh sorry, I forget this, add this attribute to your form element:
submitdisabledcontrols="true"

Open in new window


Example:
<form id="form1" runat="server" submitdisabledcontrols="true">
.........
</form>

Open in new window

Author

Commented:
Hi yv989c,

That did not work either. Same result, I do not get an email and the page does not redirect to success page.
Carlos VillegasFull Stack .NET Developer

Commented:
What .net framework are you using? all that must work for .net framework 4.0... well try this also:

Set the UseSubmitBehavior property of your button to false, example:

<asp:Button Text="Search" runat="server" ID="btn_ForgotPassword" UseSubmitBehavior="false" OnClick="btn_ForgotPassword_Click" />
Carlos VillegasFull Stack .NET Developer

Commented:
hehe I'm doing too many things at the same time, I think that is the last change that you need to do in your code to make it work, with the .net framework 4.0 also I need to set the UseSubmitBehavior="false" on the button, otherwise it will not fire the OnClick event, sorry for the confusion ;)

Author

Commented:
yv989c,

That worked. I was only able to click it once before it got disabled. What happens if there is an error. Do i need to add something to the catch block of code to enable the button again?

Also, is it a good rule of thumb that I can use your example for all of my forms where I don't want the user to click multiple times?

I have seen some Javascript stuff but if user has javascript disabled then it does not help. Also, the javascript stuff that I have used in the past does not make the button disabled which I really like in your example.
Carlos VillegasFull Stack .NET Developer

Commented:
No, you dont need add anything else, if a submit is raised in your page it will always refresh the whole page (unless you are using an ajax implementation, then this statement may or not apply), restoring your button initial state.

Also, is it a good rule of thumb that I can use your example for all of my forms where I don't want the user to click multiple times?
Yes, that is a common problem in web applications.

I have seen some Javascript stuff but if user has javascript disabled then it does not help.
Yes, and for those scenarios I have implemented server side logic, like to check the last time when that method was successfully called for that user, if was too recently I show a message indicating they need to wait more time before trying again.

Author

Commented:
Ok, can you just briefly explain what the following does below and where I may able to find more info on it to learn from?

    protected override void Render(HtmlTextWriter writer)
    {
        ClientScript.RegisterOnSubmitStatement(this.GetType(), "DisableButton", "$('#btn_ForgotPassword').attr('disabled', 'disabled')");
        base.Render(writer);
    }
Carlos VillegasFull Stack .NET Developer
Commented:
OK:

1. ClientScript (System.Web.UI.ClientScriptManager) is a utility that help you to handle your client scripts in a structured way, it is very helpful, read the documentation here:
http://msdn.microsoft.com/en-us/library/0skaxdwf.aspx

RegisterOnSubmitStatement method let you to register scripts on the client side specifically on the OnSubmit event of your page (this is before the page is submited to your server when an user click on a submit button)

2. protected override void Render(HtmlTextWriter writer)......
That method is called for you page before render the controls to html and send it back to your browser, I have to call ClientScript.RegisterOnSubmitStatement at that point because you have validators in your page, the validators also use the OnSubmit event of your page, I need that the validators register first on that event and then I register my disable button logic, otherwise when you click on your search button and something is not valid in your page your button will be disabled but you dont want that because the data in your page is not valid (e.g your email is empty), I dont know if i'm explain well my english is not very extensive. If you move this line from the Render method:
ClientScript.RegisterOnSubmitStatement(this.GetType(), "DisableButton", "$('#btn_ForgotPassword').attr('disabled', 'disabled')");

Open in new window

To your page Load event you will see what I'm talking about:
protected void Page_Load(object sender, EventArgs e)
{
    ClientScript.RegisterOnSubmitStatement(this.GetType(), "DisableButton", "$('#btn_ForgotPassword').attr('disabled', 'disabled')");
}

Open in new window

Explore More ContentExplore courses, solutions, and other research materials related to this topic.