Logout linkbutton is not firing click event - c#

I am trying to implement my login and logout through my webpage. There are two panels which toggle. On my page load, the logout panel is made invisible so that the user may only see the login link. After logging in the login panel is made invisible and the logout panel is made visible where the logout link is there for logging out. but the logout linkbutton is not even firing the click event. This is what i see in the browser window at the bottom when i try to click the logout link button
This is my aspx page-
<div>
<asp:Panel ID="LoginPanel" runat="server">
<ul class="style1">
<li>Username</li>
<li><asp:TextBox ID="LoginEmail" runat="server" Width="90%" placeholder="Email" class="form-control"></asp:TextBox></li>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Email Required" ControlToValidate="LoginEmail" ForeColor="#CC0000" Font-Italic="True"></asp:RequiredFieldValidator>
<li>Password</li>
<li><asp:TextBox ID="LoginPassword" runat="server" Width="90%" placeholder="Password" class="form-control" TextMode="Password"></asp:TextBox></li>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Password Required" ControlToValidate="LoginPassword" ForeColor="#CC0000" Font-Italic="True"></asp:RequiredFieldValidator>
<li><asp:Button ID="LoginButton" runat="server" Text="Login" class="btn btn-default" onclick="LoginButton_Click"/>
New User?<asp:HyperLink ID="new_user" runat="server" NavigateUrl="Registration.aspx">Register Here</asp:HyperLink></li>
</ul>
</asp:Panel>
<asp:Panel ID="LogoutPanel" runat="server">
<asp:LinkButton ID="LogoutLink" runat="server" Text="Logout"
onclick="LogoutLink_Click" />
</asp:Panel>
</div>
This is my cs code-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
public partial class UserMasterPage : System.Web.UI.MasterPage
{
ConnectionClass cl;
SqlDataReader dr;
string sql;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LogoutPanel.Visible = false;
cl = new ConnectionClass();
}
}
protected void LoginButton_Click(object sender, EventArgs e)
{
sql = "select Id, Email_, Password_, Block from MemberLogin where Email_='" + LoginEmail.Text + "'";
cl = new ConnectionClass();
cl.establishConnection();
cl.createReaderCommand(sql);
dr = cl.executeReaderCommand();
if (dr.HasRows)
{
if (LoginPassword.Text == dr["Password_"].ToString())
{
if (dr["Block"].ToString() == "False")
{
Session["user"] = dr[0].ToString();
LoginPanel.Visible = false;
LogoutPanel.Visible = true;
//Response.Write("login successful");
}
}
}
cl.closeConnection();
}
protected void LogoutLink_Click(object sender, EventArgs e)
{
Session.Abandon();
Response.Redirect("AdminLogin.aspx");
}
}
This is on my master page. I need to solve this problem very soon. Please help me with this.Thanks in advance.

The __DoPostBackWithOptions call associated with the LinkButton is related to the presence of the validators in your page. Setting CausesValidation to false would replace it by the "regular" __doPostBack:
<asp:LinkButton ID="LogoutLink" runat="server" CausesValidation="false" ... />
The validators shown in your markup being in a Panel with Visible = false, they should not be active. But since I don't see anything else that could prevent the postback, turning off the validation for the LinkButton would at least eliminate that possible cause.
By the way, if you have many controls and validators in your form, you may consider grouping them with validation groups. That would allow each button (or other controls causing a postback) to trigger only the relevant validators:
<asp:TextBox ID="txt1a" runat="server" ValidationGroup="Group1" />
<asp:RequiredFieldValidator ID="rfv1a" runat="server" ControlToValidate="txt1a" ValidationGroup="Group1" Text="*" ForeColor="Red" />
<asp:TextBox ID="txt1b" runat="server" ValidationGroup="Group1" />
<asp:RequiredFieldValidator ID="rfv1b" runat="server" ControlToValidate="txt1b" ValidationGroup="Group1" Text="*" ForeColor="Red" />
<asp:Button ID="btn1" runat="server" Text="Button1" ValidationGroup="Group1" />
<br />
<asp:TextBox ID="txt2a" runat="server" ValidationGroup="Group2" />
<asp:RequiredFieldValidator ID="rfv2a" runat="server" ControlToValidate="txt2a" ValidationGroup="Group2" Text="*" ForeColor="Red" />
<asp:TextBox ID="txt2b" runat="server" ValidationGroup="Group2" />
<asp:RequiredFieldValidator ID="rfv2b" runat="server" ControlToValidate="txt2b" ValidationGroup="Group2" Text="*" ForeColor="Red" />
<asp:Button ID="btn2" runat="server" Text="Button2" ValidationGroup="Group2" />
In the example above, a click on btn1 would cause a postback even if txt2a is empty, because they don't belong to the Group1 validation group.

Related

ASP.net The name 'userName' does not exist in the current context

I've clicked over 20 links trying to solve this problem in different websites.
Please help me
So I am trying to do a simple log in authentication.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
public partial class Account_Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void loginButton_Click(object sender, EventArgs e)
{
if(FormsAuthentication.Authenticate(UserName.Text, Password.Text)
{
}
}
}
But an error message pops up saying "The name 'userName' does not exist in the current context' and The name 'Password' does not exist in the current context.
Here is the aspx code
<%# Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="Account_Login" %>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" Runat="Server">
<hgroup class="title">
<h1>Login Page</h1>
</hgroup>
<section id="loginForm">
<asp:Login ID="Login1" runat="server" ViewStateMode="Disabled" RenderOuterTable="false">
<LayoutTemplate>
<p class="validation-summary-errors">
<asp:Literal runat="server" ID="FailureText" />
</p>
<fieldset>
<legend>Log in Form</legend>
<ol>
<li>
<asp:Label ID="Label1" runat="server" AssociatedControlID="UserName">User name</asp:Label>
<asp:TextBox runat="server" ID="UserName" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="UserName" CssClass="field-validation-error" ErrorMessage="The user name field is required." />
</li>
<li>
<asp:Label ID="Label2" runat="server" AssociatedControlID="Password">Password</asp:Label>
<asp:TextBox runat="server" ID="Password" TextMode="Password" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="Password" CssClass="field-validation-error" ErrorMessage="The password field is required." />
</li>
<li>
<asp:CheckBox runat="server" ID="RememberMe" />
<asp:Label ID="Label3" runat="server" AssociatedControlID="RememberMe" CssClass="checkbox">Remember me?</asp:Label>
</li>
</ol>
<asp:Button ID="loginButton" runat="server" CommandName="Login" Text="Log in" OnClick="loginButton_Click" />
</fieldset>
</LayoutTemplate>
</asp:Login>
<p>
Register
if you don't have an account.
</p>
</section>
Please help me :)
UserName is inside Login control, so you need to access it via Login1 control.
string userName = Login1.UserName;
string password = Login1.Password;
Another problem in your code is, you should not use loginButton_Click event if you use Login control.
In stead, you need to use the following depending on your satiation -
LoggingIn
LoggedIn
C# is case sensitive.
it should be Username with a capital "U" as per your control ID:
<asp:TextBox runat="server" ID="UserName" />
your code should be:
protected void loginButton_Click(object sender, EventArgs e)
{
if(FormsAuthentication.RedirectFromLoginPage(UserName.Text, Password.Text)
{
}
}
EDIT - Noticed the control in question is within a usercontrol so the code should now be:
protected void loginButton_Click(object sender, EventArgs e)
{
if(FormsAuthentication.RedirectFromLoginPage(Login1.UserName.Text, Password.Text)
{
}
}
however you still did have a typo in the UserName ID
Code is case sensitive.
if(FormsAuthentication.RedirectFromLoginPage(UserName.Text, Password.Text)
{
}

Validation on a button click using RequiredFieldValidator

In the past, on button click events, I've validated without using RequiredFieldValidators. However, I thought I'd learn about them and implement them.
My old approach:
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (txtSubject.Text.Equals("") || txtEmail.Text.Equals("") || txtComments.Text.Equals(""))
{
lblMessage.Text = "Please check all fields have been entered.";
}
//else if ...further validation statements e.g. check lengths
}
However, using RequiredFieldValidators with the same example, am I correct in saying that I don't have to check again if (txtSubject.Text.Equals("") || txtEmail.Text.Equals("") || txtComments.Text.Equals("")) like below or is it good practice to do so?
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//...further validation statements e.g. check lengths
try
{
SendMail();
}
catch (Exception)
{
}
}
}
If I should still include the line, it should go at the beginning of the if (Page.IsValid), right?
HTML code:
<p>Contact Form</p>
<p>
Your name:
<asp:RequiredFieldValidator ID="rfvName" runat="server" ErrorMessage="*"
ControlToValidate="txtName" ValidationGroup="save" /><br />
<asp:TextBox ID="txtName" runat="server" Width="250px" /><br />
Your email address:
<asp:RequiredFieldValidator ID="rfvEmail" runat="server" ErrorMessage="*"
ControlToValidate="txtEmail" ValidationGroup="save" /><br />
<asp:TextBox ID="txtEmail" runat="server" Width="250px" />
<asp:RegularExpressionValidator runat="server" ID="rfvEmail2"
SetFocusOnError="true" Text="Example: email#gmail.com" ControlToValidate="txtEmail"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*" Display="Dynamic"
ValidationGroup="save" /><br />
Subject:
<asp:RequiredFieldValidator ID="rfvSubject" runat="server" ErrorMessage="*"
ControlToValidate="txtSubject" ValidationGroup="save" /><br />
<asp:TextBox ID="txtSubject" runat="server" Width="400px" /><br />
Comments:
<asp:RequiredFieldValidator ID="rfvComments" runat="server" ErrorMessage="*"
ControlToValidate="txtComments" ValidationGroup="save" /><br />
<asp:TextBox ID="txtComments" runat="server" TextMode="MultiLine" Rows="10" Width="400px" />
</p>
<p>
<asp:Button ID="btnSubmit" runat="server" Text="Send" OnClick="btnSubmit_Click" ValidationGroup="save" />
</p>
<p>
<asp:Label ID="lblMessage" runat="server" Visible="true" />
</p>
why dont you do the following?
Page.Validate("save");
if (Page.IsValid)
{
//Continue with your logic
}
else
{
//Display errors, hide controls, etc.
}
This only fires your validation group and furthermore , you can use a validation summary to display your message about the correct formats of the text boxes.
And you can display an error message then and there to display the correct format.

Validate() function doesn't fire

Here is my button.
<asp:Button ID="btnNext" runat="server" Text="Next" Style="display: none" OnClick="btnNext_Click" CausesValidation="true" ValidationGroup="vgLinR"/>
When I write ValidationGroup="vgLinR" in aspx side validation works. But I have 2 different validation group. So I need fire these 2 validation group in one button.
so I write that code at code behind :
protected void btnNext_Click(object sender, EventArgs e)
{
Page.Validate("vgLinR");
Page.Validate("vgLogR");
}
but it doesn't work. Why? How can I do that?
it will work for you ..
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="*" Font-Size="Medium" ForeColor="Red" ValidationGroup="group 1">*</asp:RequiredFieldValidator>
<br />
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="TextBox2" ErrorMessage="*" Font-Size="Medium" ForeColor="Red" ValidationGroup="group 1">*</asp:RequiredFieldValidator>
<br />
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="TextBox3" ErrorMessage="*" Font-Size="Medium" ForeColor="Red" ValidationGroup="group 2">*</asp:RequiredFieldValidator>
<br />
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
<br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="TextBox4" ErrorMessage="*" Font-Size="Medium" ForeColor="Red" ValidationGroup="group 2">*</asp:RequiredFieldValidator>
<br />
<br />
<br />
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="validate all" OnClick="Button1_Click"/> <br />
</div>
</form>
and write code for onclick event
protected void Button1_Click(object sender, EventArgs e)
{
Page.Validate();
}
try this
public bool Validate()
{
var isValid = false;
Page.Validate("vgLinR");
isValid = Page.IsValid;
if (isValid)
{
Page.Validate("vgLogR");
isValid = Page.IsValid;
}
return isValid;
}
Saw your answer reply for Amit a bit too late. I have updated my answer accordingly. May be you can use a similar idea if it does not fit your requirement.
In my code I am using a single ValidationSummary control without any validation group specified. Also remove the validation group from your button. Textbox a and b can be in one validation group, vg1 whereas Textbox c and d can be in another, vg2. I am not sure how you have set up your validation groups.
protected void btnNext_Click(object sender, EventArgs e)
{
if (RadioButton1.Checked)
{
Page.Validate("vg1");
ValidationSummary1.ValidationGroup = "vg1";
}
else if (RadioButton2.Checked)
{
Page.Validate("vg2");
ValidationSummary1.ValidationGroup = "vg2";
}
if (Page.IsValid)
{
//do something in here
}
}
The above code will do a server side validation. To do it on the client side as well, you would need to add a bit of javascript.
Look at another post to enable/disable Validation Group from JQuery or Javascript

ASP.net Change Password Validator

I am working on a eCommerce project which has an admin panel and shopping panels.
I have finished programming and now testing every single aspx and cs files by manually.
The problem is, I have a change password feature which is related with session and Database. The problem is I have a validators in my aspx file but they won't work. Here my codes are;
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<asp:Panel ID="Panel1" runat="server" DefaultButton="btnChange">
<div class="userForm">
<div class="formTitle">
Change Your Password
</div>
<div class="formContent">
<asp:TextBox ID="txtPassword" placeholder="Type your new password" runat="server" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txtPassword"
ErrorMessage="RequiredFieldValidator" ForeColor="Red" Display="Dynamic" ValidationGroup="signup">Enter a password</asp:RequiredFieldValidator>
<br />
<asp:TextBox ID="txtAgainPassword" placeholder="Repeat your new password" runat="server" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator9" runat="server" BorderColor="Red"
ControlToValidate="txtAgainPassword" Display="Dynamic" ErrorMessage="Enter password again."
ForeColor="Red" ValidationGroup="signup"></asp:RequiredFieldValidator>
<asp:CompareValidator ID="CompareValidator1" runat="server" ControlToCompare="txtPassword"
ControlToValidate="txtAgainPassword" Display="Dynamic" ErrorMessage="Password don't match."
ForeColor="Red" ValidationGroup="signup"></asp:CompareValidator>
<br />
<asp:Button ID="btnChange" runat="server" Text="Submit" OnClick="btnChange_Click" />
<br />
<asp:Label ID="lblError" Visible="False" ForeColor="Green" runat="server"></asp:Label></div>
</div>
</asp:Panel>
</asp:Content>
and the .cs part is below
protected void btnChange_Click(object sender, EventArgs e)
{
using (ZirveMarketDBEntities context = new ZirveMarketDBEntities())
{
// Atanan sessiona gore user bilgisini al - guvenlik icin onemli
int id = (int)Session["CustomerID"];
Customer cust = context.Customers.Where(i => i.CustomerID == id).FirstOrDefault();
cust.Password = txtPassword.Text;
context.SaveChanges();
}
lblError.Visible = true;
lblError.Text = "Password successfully updated";
}
The problem is, I have a 2 box for new password and type new password. Even if they are null, even if they don't match the password still changes with the value of the first part. I don't want to run server side code if they don't match or null. What am I doing wrong? Helps are pretty apreciated.
Add the 'ValidationGroup="signup"' attribute to the btnChange button.
I'd also recommend adding the below to the click event (before anything else) in case Javascript is disabled on the client:
Page.Validate("signup");
if (!Page.IsValid)
{
return;
}
You have validation groups specified on the validators, but not on the Button. Try adding the validation group to the button as well.

Form submits on browser refresh

I am having trouble to find a solution to stop form submission on click of the browser's refresh button.
This is the Login form I have:
<asp:Login ID="EMSLogin" runat="server" OnAuthenticate="EMSLogin_Authenticate">
<LayoutTemplate>
<asp:Panel ID="Panel1" runat="server" CssClass="wrapper">
<asp:Panel ID="Panel2" runat="server" CssClass="holder">
<asp:Panel ID="Panel3" runat="server" CssClass="loginBox one_edge_shadow">
<h1>
Login Credentials</h1>
<asp:Panel ID="Panel4" runat="server" CssClass="name topmargin">
<asp:Panel ID="Panel5" runat="server" CssClass="label">
<asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName">User Name:</asp:Label>
</asp:Panel>
<asp:Panel ID="Panel6" runat="server" CssClass="textBox">
<telerik:RadTextBox ID="UserName" runat="server" Height="16px" Width="165px" Font-Size="14px"
Font-Names="Arial Sans-Serif" ToolTip="Enter your valid login name" />
<asp:RequiredFieldValidator ID="UserNameRequired" runat="server" ControlToValidate="UserName"
ValidationGroup="EMSLogin">*</asp:RequiredFieldValidator>
</asp:Panel>
<br class="clearfix" />
</asp:Panel>
<asp:Panel ID="Panel7" runat="server" CssClass="name topmargin">
<asp:Panel ID="Panel8" runat="server" CssClass="label">
<asp:Label ID="PasswordLabel" runat="server" AssociatedControlID="Password">Password:</asp:Label>
</asp:Panel>
<asp:Panel ID="Panel9" runat="server" CssClass="textBox">
<telerik:RadTextBox ID="Password" runat="server" TextMode="Password" Height="16px"
Width="165px" Font-Size="14px" Font-Names="Arial Sans-Serif" ToolTip="Enter your valid password" />
<asp:RequiredFieldValidator ID="PasswordRequired" runat="server" ControlToValidate="Password"
ValidationGroup="EMSLogin">*</asp:RequiredFieldValidator>
</asp:Panel>
<br class="clearfix" />
<telerik:RadButton ID="LoginButton" runat="server" CommandName="Login" Text="Log In"
CssClass="loginButton" Font-Size="14px" Width="100px" ValidationGroup="EMSLogin"
ToolTip="Click to log in" />
</asp:Panel>
</asp:Panel>
</asp:Panel>
</asp:Panel>
</LayoutTemplate>
</asp:Login>
And in the backend:
protected void Page_Load(object sender, EventArgs eventArgs) {
log.Info("=============INSIDE Page_Load======");
DataBind();
LoginErrorWindow.VisibleOnPageLoad = false;
}
protected void EMSLogin_Authenticate(object sender, AuthenticateEventArgs e) {
log.Info("=============INSIDE EMSLogin_Authenticate======");
RadTextBox UserName = EMSLogin.FindControl("UserName") as RadTextBox;
RadTextBox Password = EMSLogin.FindControl("Password") as RadTextBox;
if (Membership.ValidateUser(UserName.Text, Password.Text)) {
FormsAuthentication.RedirectFromLoginPage(UserName.Text, false);
} else {
LoginErrorWindow.NavigateUrl = EMSApplication.Web.Utils.NavigationUtils.GetLoginErrorDialogURL();
LoginErrorWindow.VisibleOnPageLoad = true;
}
}
Now after one login failed if I press the refresh button the method EMSLogin_Authenticate is executing again. And before reload it is showing:
How can I solve this?
Do a Response.Redirect to an error page after the login has failed.
See the PRG pattern on Wikipedia.
Post/Redirect/Get (PRG) is a web development design pattern that prevents some duplicate form submissions, creating a more intuitive interface for user agents (users). PRG implements bookmarks and the refresh button in a predictable way that does not create duplicate form submissions.

Categories