Pass username & password to an invisible Login Control to validate? - asp.net

In my master page, on the menu there is an icon which uses Jquery to slide, showing 2 textboxes (username, password) for users to enter & 1 submit button. My idea is that after submitting, I get values of these 2 fields to assigned it to an invisible Login Control in my MasterPage, then validate automatically.
I could get values and assign but problem is I don't know how to trigger the Login button in Login Control (how to force it to process information)? the DataBind() func doesn't work
Master.master
<div id="login">
<p>
<asp:Login ID="Login2" runat="server" DestinationPageUrl="~/Index.aspx" LoginButtonStyle-CssClass="button_login"
TextBoxStyle-CssClass="input-name" Visible="false">
</asp:Login>
<asp:TextBox ID="inputUser" CssClass="input-name" Text="Username" runat="server"></asp:TextBox>
<asp:TextBox ID="inputPassword" CssClass="input-pass" Text="Password" runat="server"
TextMode="Password"></asp:TextBox>
<asp:Button ID="btn_login" CssClass="button_login" runat="server" OnClick="triggerLogin" />
</p>
</div>
Main.master.cs:
protected void triggerLogin(object sender, EventArgs e)
{
Login2.UserNameLabelText = inputUser.Text;
Login2.PasswordLabelText = inputPassword.Text;
Login2.DataBind();
}
Actually I already have a login page which processes individually, is it possible to pass information to that page to process?

You can add your username and password int o a session.
Something like:
Session["user"] = inputUser.Text;
Session["pass"] = inputPassword.Text;
By using that you can access the username,password in your pages.
var myusername = Session["user"].ToString();
var mypassword= Session["pass"].ToString();
Check this on MSDN:
ASP.NET State Management Overview
How to: Pass Values Between ASP.NET Web Pages
Regards

Yeah, I've found out the solution, without having to use Login Control. I can do it manually.
<asp:TextBox ID="inputUser" CssClass="input-name" Text="Username" runat="server"></asp:TextBox>
<asp:TextBox ID="inputPassword" CssClass="input-pass" Text="Password" runat="server"
TextMode="Password"></asp:TextBox>
<asp:Button ID="btn_login" CssClass="button_login" runat="server" OnClick="triggerLogin" />
Codebehind:
protected void triggerLogin(object sender, EventArgs e)
{
TextBox txtbxInputUser = (TextBox)Page.Master.FindControl("inputUser");
TextBox txtbxInputPass = (TextBox)Page.Master.FindControl("inputPassword");
Label samplelabel1 = (Label)Page.Master.FindControl("sampleLabel1");
if (System.Web.Security.Membership.ValidateUser(txtbxInputUser.Text, txtbxInputPass.Text))
{
System.Web.Security.FormsAuthentication.SetAuthCookie(txtbxInputUser.Text, false);
}
else
{
Response.Redirect("Login.aspx?Attempt=wrong");
}
}

Related

Change the buttons if user is logged

I have this navbar which shows some links on the left side and Sign in/sign up links on the right one. I want to check if the user is logged and if it is, instead of the sign in/up links, to show his name. I know how to check if there is something in the session in the code behind, but I have a hard time changing the view. Thanks in advance.
You can do this. It uses the build in Request.IsAuthenticated to show/hide controls on the page. And you can use the LoginStatus Control for generating a login/logout link. See Microsoft site for more info.
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="Login.aspx">Login</asp:HyperLink>
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
<asp:LoginStatus ID="LoginStatus1" runat="server" />
Code behind
protected void Page_Load(object sender, EventArgs e)
{
if (Request.IsAuthenticated)
{
HyperLink1.Visible = false;
Label1.Text = User.Identity.Name;
}
}
You can use inline code,
<% if (Session["User"] != null) { %>
//button goes here
<% } %>

Simple HTTP Post returning empty Request.Form

I am trying a simply HTTP post to post data from one form to another in asp.net.
sender page code
<form id="form1" runat="server" method="post" action="CILandingPage.aspx">
<asp:TextBox name="txtUname" runat="server" Width="180px"></asp:TextBox>
<asp:TextBox name="txtPassword" runat="server" TextMode="Password" Width="180px"></asp:TextBox>
<asp:TextBox name="txtTransaction" runat="server" Width="180px"></asp:TextBox>
and the receiver page has code
lblUserName.Text = Request.Form["txtUname"].ToString();
lblPassword.Text = Request.Form["txtPassword"].ToString();
lblTransactionID.Text = Request.Form["txtPassword"].ToString();
it throws NullReferenceException because Request.Form object is empty.
what am i missing?
Set the PostBackUrl property for the control to the URL of the page to which you want to post the ASP.NET Web Forms page.
Remove action and add PostBackUrl into Button.Instead name use ID property value.
In Default.aspx
<form id="form1" runat="server" method="post">
<div>
<asp:TextBox ID="TextBox1" name="txtUname" runat="server" Width="180px"></asp:TextBox>
<asp:TextBox ID="TextBox2" name="txtPassword" runat="server" TextMode="Password" Width="180px"></asp:TextBox>
<asp:TextBox ID="TextBox3" name="txtTransaction" runat="server" Width="180px"></asp:TextBox>
<asp:Button ID="button" PostBackUrl="~/CILandingPage.aspx" runat="server" />
</div>
</form>
In CILAndinaPage.aspx.cs
using System;
public partial class CILandingPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Response.Write(Request.Form["TextBox1"].ToString() +Environment.NewLine);
Response.Write(Request.Form["TextBox2"].ToString() + Environment.NewLine);
Response.Write(Request.Form["TextBox3"].ToString());
}
}
}
You may use PreviousPage reference as below:
protected void Page_Load(object sender, EventArgs e)
{
// first check if we had a cross page postback
if ( (PreviousPage != null) && (PreviousPage.IsCrossPagePostBack))
{
Page previousPage = PreviousPage;
TextBox UserName= (TextBox)previousPage.FindControl("txtUname");
TextBox Password= (TextBox)previousPage.FindControl("txtPassword");
// we can now use the values from TextBoxes and display them in two Label controls..
lblUserName.Text = UserName.Text;
blPassword.Text = Password.Text;
}
}
This code in Page_Load will get referenced to previous page that has posted the data & helps you get the same on the destination page.
Hope this helps!!
Since you are posting cross-page, it is likely that collection item (txtPassword) doesn't exist. You can try setting the ClientIdMode of each control to static so that the id used in the HTTP post matches what you are looking for in the .Form collection on the target page.
Check out this article for more info on cross-page posting: https://msdn.microsoft.com/en-us/library/ms178139%28v=vs.140%29.aspx
Use your browser debugging tool (F12) to see what is transmitted in the HTTP Post body.

Load another web page based on value of drop down list in asp.net

I am trying to redirect to another web page when the user selects the drop down list and the user should be redirected to another web page as soon as the user clicks the submit button.This is my code for drop down list and button.On clicking the "click to proceed" button the user should be taken to next web page depending on list selection.
Iam new to .Net Please help thanks in advance !!
<asp:DropDownList ID="DropDownList1" runat="server"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem Value="-1">Select User</asp:ListItem>
<asp:ListItem Value="staff">Staff</asp:ListItem>
<asp:ListItem Value="student">Student</asp:ListItem>
</asp:DropDownList>
<br />
<br />
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="Click to Proceed" />
In your Button1_Click event, use the Response.Redirect method to send people to the appropriate page.
http://msdn.microsoft.com/en-us/library/a8wa7sdt%28v=vs.110%29.aspx
Following can be helpful for you.
protected void Button1_Click(object sender, EventArgs e)
{
string sel_val = DropDownList1.SelectedValue; // use sel_val to apply if, else logic to redirect to
// some possible examples
if (sel_val != "-1") // as SelectedValue is string
{
// assuming there is staff.aspx, and you want to redirect to that page on selecting staff, this is just an example
Response.Redirect(sel_val + ".aspx"); // use this to redirect to required page
}
}
Also change aspx code like this.Note i have changed OnClick from onclick.
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click"
Text="Click to Proceed" />

How do I load two ASP.NET UserControls on Demand?

I want load two user controls on demand.
asp:UpdatePanel ID="UpdatePanel1" runat="server"
ContentTemplate
asp:Button ID="Button1" runat="server" Text="Button" UseSubmitBehavior="false"
OnClick="Button1_Click" /
div id='Div_UserControlPlace' enableviewstate="true" runat="server"
/div
/ContentTemplate
Triggers
asp:PostBackTrigger ControlID="Button1" /
/Triggers
/asp:UpdatePanel
asp:UpdatePanel ID="UpdatePanel2" runat="server"
ContentTemplate
asp:Button ID="Button2" runat="server" Text="Button" UseSubmitBehavior="false"
OnClick="Button2_Click" /
div id='Div_UserControlPlace2' enableviewstate="true" runat="server"
/div
/ContentTemplate
aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Control FeaturedProductUserControl = new Control();
FeaturedProductUserControl = LoadControl("WebUserControl1.ascx");
FeaturedProductUserControl.EnableViewState = true;
Div_UserControlPlace.Controls.Add(FeaturedProductUserControl);
}
protected void Button2_Click(object sender, EventArgs e)
{
Control FeaturedProductUserControl2 = new Control();
FeaturedProductUserControl2 = LoadControl("WebUserControl2.ascx");
FeaturedProductUserControl2.EnableViewState = true;
Div_UserControlPlace2.Controls.Add(FeaturedProductUserControl2);
}
I load the first user control by clicking on the first button - this works properly but when I click on the other button to load the second UserControl, the first UserControl disappears and the second UserControl loads.
Thanks
IFA_User
You should use the Placeholder control to dynamically add your controls to the form.
Take a look at my last responses about dynamic controls:
OnClick event of dynamically created LinkButtons is not working
Dynamically Added DropDownlists Are Not Firing SelectedIndexChanged Event
Dynamically create an ImageButton
Now I already have some code working for demo purpose, each dynamic user controls keeps its state across post backs
This is the output:
ASPX
<asp:PlaceHolder runat="server" ID="addresses" /><br />
<asp:Button Text="Add Address" runat="server" ID="addAddress" OnClick="addAddress_Click" />
ASPX Code behind
protected void Page_PreLoad(object sender, EventArgs e)
{
for (int i = 0; i < this.DynamicControlsCount; i++)
{
var c = this.LoadControl("~/AddressControl.ascx");
this.addresses.Controls.Add(c);
}
}
protected void addAddress_Click(object sender, EventArgs e)
{
this.DynamicControlsCount++;
var c = this.LoadControl("~/AddressControl.ascx");
this.addresses.Controls.Add(c);
}
protected int DynamicControlsCount
{
get
{
if (this.ViewState["ac"] == null)
{
return 0;
}
return (int)this.ViewState["ac"];
}
set
{
this.ViewState["ac"] = value;
}
}
ASCX
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="AddressControl.ascx.cs" Inherits="WebApplication1.AddressControl" %>
<asp:Panel ID="Panel1" runat="server" GroupingText="Address" DefaultButton="btnSave">
Street: <asp:TextBox runat="server" ID="txtStreet" /><br />
City: <asp:TextBox runat="server" ID="txtCity" /><br />
<asp:Button Text="Save" runat="server" ID="btnSave" OnClick="btnSave_Click" />
</asp:Panel>
<asp:Panel runat="server" GroupingText="Address Summary" Visible="false" ID="summary">
<asp:Label ID="lblStreet" runat="server" /><br />
<asp:Label ID="lblCity" runat="server" />
</asp:Panel>
ASCX Code behind
protected void btnSave_Click(object sender, EventArgs e)
{
this.summary.Visible = true;
this.lblCity.Text = "Selected city: " + this.txtCity.Text;
this.lblStreet.Text = "Selected street: " + this.txtStreet.Text;
}
When a user control is created in the HTML, asp.net will persist across postbacks without any user interaction. But if you are loading them programatically (dynamically), they will not persist accross postbacks. So if you load them programmatically, you have the added task of persisting them programmatically as well. Use the ViewState (or Session I suppose) to store what has been loaded and perhaps any other necessary information that needs to be loaded between postbacks. Every single postback will require you to reload every control or else they will disappear.
There are couple of ways of doing it:
U can load the UserControls using Ajax. Benefit of using Ajax, is ur page does not get post back, thus for example, on click event of Button1, call a ajax(traditional/Jquery) to load UserControl1, and on button click of Button2 User control2.
Put the two button in two different updated panel, by doing this the click event will only refresh a part of ur page.
U have to save somewhere (ViewState/Session),which buttons are clicked, and upon clicking of any button check the value of that variable, and explicit load the control.
Points to note - If u want to get ur data back when ur page made a complete postback, then u have to add the controls keeping in mind the Page load event cycle.

Need help in login validation using javascript

Please could somebody point me out what is the error here? Using javascript i am validating the user input. When i click the login button without checking the javascript function, it goes to the welcome page. Here is my code:
<script type="text/javascript">
function validLogin()
{
if(document.getElementById("txtUserName").value == "")
{
alert("Please enter your UserName");
return false;
}
if(document.getElementById("txtPassword").value == "")
{
alert("Please enter your Password");
return false;
}
}
</script>
protected void Page_Load(object sender, EventArgs e)
{
BtnLogin.Attributes.Add("onClick","return ValidLogin();");
}
I see that you're using ASP .NET (the Page_Load event on your posted code).
I think that will be easier to handle validation through ASP .NET Validation Controls, i.e. RequiredFieldValidator.
Check your case on return ValidLogin(); it doesn't match.
P.S.: I hope you aren't performing all user validation client-side.
It would probably be easier to user ASP .NET validation controls, here's a sample:
User Name:
<asp:TextBox ID="UserName" runat="server" />
<asp:RequiredFieldValidator
ID="UserNameValidator"
ControlToValidate="UserName"
ErrorMessage="User Name Required"
runat="server" />
Password:
<asp:TextBox ID="Password" runat="server" />
<asp:RequiredFieldValidator
ID="PasswordValidator"
ControlToValidate="Password"
ErrorMessage="Password Required"
runat="server" />
first make sure it's not a difference in case... your javascript function is validLogin and in Page_Load you have ValidLogin

Resources