Change the buttons if user is logged - asp.net

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
<% } %>

Related

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.

How to avoid Page_Load() on button click?

I have two buttons, preview and Save. With help of preview button user can view the data based on the format and then can save.
But when preview is clicked, one textbox attached to ajaxcontrol (Calender) becomes empty and user have to fill the date before saving. How to handle this? On preview click i get the details to show the data in layout.
<asp:TextBox ID="txtDate" ReadOnly="true" runat="server"></asp:TextBox>
<div style="float: right;">
<asp:ImageButton ID="imgcalender1" runat="server" ImageUrl="~/images/calendar.png"
ImageAlign="Bottom" />
<asp:CalendarExtender ID="ajCal" TargetControlID="txtpublishDate" PopupButtonID="imgcalender1"
runat="server">
</asp:CalendarExtender>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" ValidationGroup="group1" runat="server" ControlToValidate="txtDate"
ForeColor="Red" Font-Bold="true" ErrorMessage="*"></asp:RequiredFieldValidator>
</div>
<asp:Button ID="btnPreview" runat="server" Text="Preview" OnClick="btnPreview_Click" />
<asp:Button ID="btnsubmit" runat="server" ValidationGroup="group1" Text="Save" OnClick="btnsubmit_Click" />
Use Page.IsPostback() in your aspx code (server-side). Like this:
private void Page_Load()
{
if (!IsPostBack)
{
// the code that only needs to run once goes here
}
}
This code will only run the first time the page is loaded and avoids stepping on user-entered changes to the form.
From what I am understanding the preview button is causing a postback and you do not want that, try this on your preview button:
<asp:button runat="server".... OnClientClick="return false;" />
similarly this also works:
YourButton.Attributes.Add("onclick", return false");
Edit:
it seems the answer to the user's question was simple change in the HTML mark up of the preview button
CausesValidation="False"
you can put your code in
Page_Init()
{
//put your code here
}
instead of
Page_Load()
{
//code
}
I had the same problem and the solution above of "CausesValidation="False"" and even adding "UseSubmitBehavior="False"" DID NOT work - it still called "Page_Load" method.
What worked for me was adding the following line up front in Page_Load method.
if (IsPostBack) return;
I am mentioning this if it helps someone (I meant to comment above but StackOverflow did not allow me to comment because I am a new user - hence a new reply).
Try adding this to the buttons properties in the aspx page.
OnClientClick="return false;"
For my the #tgolisch answer worked better, maybe it's because i'm still a rookie.
I was trying to load a simple captcha in my WebForm and end up using a Reference Type in the Page_Load event and in a Button Click event (for a code snippet).
In the end i only have to edit some things and it's done:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var captchaText = generateCaptchaCode(5);
lblCaptcha.Text = captchaText;
}
}
protected void btnCheckCaptcha_Click(object sender, EventArgs e)
{
if (txtCaptchaCode.Text == lblCaptcha.Text)
lblMessage.Text = "Right input characters";
else
lblMessage.Text = "Error wrong characters";
}
form1.Action = Request.RawUrl;
Write this code on page load then page is not post back on button click

ASP.Net and postback

I have a form for people to put in info on my contact page. I'm trying to figure out how once they click submit to NOT show the form anymore and show a simple thankyou.
Thank You
Create a multiview control with 2 views.Place all your controls into one and a "thank you" message in the other and toggle the ActiveViewIndex on submit click
The simplest way would just be to use Panel controls:
<asp:Panel ID="pnlForm" runat="server">
... form here ...
<asp:Button ID="btnSubmit" OnClick="btnSubmit_Click" Text="Submit" runat="server" />
</asp:Panel>
<asp:Panel ID="pnlThankYou" Visible="False" runat="server">
Thanks!
</asp:Panel>
C#
protected void btnSubmit_Click(object sender, EventArgs e)
{
pnlForm.Visible = false;
pnlThankYou.Visible = true;
}
Try to put both sections in separate divs and make divs runat=server
and set the div which not required visible to false or just add attribute display to hide at server side
and show the other div by visible true or by attribute to block

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.

Pass username & password to an invisible Login Control to validate?

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");
}
}

Resources