How do I hide the "Register" link after user successfully logs in? - asp.net

A user opens our web app and is automatically taken to the default page.
While on default page, if the user has not logged in or created an account, the Register or Login link is displayed at the top of the page.
<table bgcolor="#003366" width="100%">
<tr><td align="right"><span style=" color:darkOrange;font-weight:bold">Login or Register</span></td></tr></table>
This is fine.
However, after user successfully logged in, s/he is redirected to his/her page.
The problem is that the user clicks the default page for whatever reason, the Register or Log in link appears again.
Is there a way to hide this link as long as the user is logged in and only show it after the user logs off?
Thanks in advance for your help.
This is the change I made so far, added label control:
<table bgcolor="#003366" width="100%">
<tr><td align="right"><span style=" color:darkOrange;font-weight:bold"><label id="loginId" runat="server" Text="Login / Register"></label></span></td></tr></table>

Based on the fact that your link is pointing to a login.aspx page, I can see that you are probably using the Web Forms section of asp.net
Usually when working with Authentication and showing/hiding elements on a page within Web Forms, you can make use of some asp.net controls.
If you are using the build in .net Membership provider, then there is a control called the Login View. This is a simple control that allows you to show different content when a user is Logged in/out.
You can do something as simple as this;
<asp:loginview ID="Loginview1" runat="server">
<AnonymousTemplate>
Login / Register
</AnonymousTemplate>
<LoggedInTemplate>
Logout
</LoggedInTemplate>
</asp:loginview>
This will automatically show/hide the correct content.
You can also make use of any server side control and using the Visible property of this. So in your code you can set controls to be visible or not depending on the logged in status.
Also you could wrap your code within a <asp:Panel> then just show hide depending;
<asp:Panel id="pnlLoggedOut" runat="server" Visible="True">
<span style=" color:darkOrange;font-weight:bold">Login or Register</span>
</asp:Panel>
<asp:Panel id="pnlLoggedIn" runat="server" Visible="False">
<span style=" color:darkOrange;font-weight:bold">Logout</span>
</asp:Panel>
In your code behind you can show either or.
Another way is to just have your <a> tag as a server control. You can then update the text and hyper link depending on the logged in status.
<asp:HyperLink ID="hlLoginStatus" runat="server" NavigateUrl="Login.aspx" Text="Login / Register" />
In your code behind if the user is logged in, then you can change the NavigateUrl and the Text property.

If you want to maintain your code, as much as possible, then I recommend wrapping your markup with a control that can be accessed server-side, like this:
<asp:Panel id="PanelLogin" runat="server" Visible="True">
<table bgcolor="#003366" width="100%">
<tr>
<td align="right">
<span style=" color:darkOrange;font-weight:bold">Login or Register</span>
</td>
</tr>
</table>
</asp:Panel>
Now in your code-behind Page_Load event, you can check to see if the user has logged in or not. I suggest you store whether or not they are logged in cache (i.e. Session value IsLoggedOn). You will toggle the visibility of the ASP.NET Panel, based upon the value of IsLoggedOn, like this:
protected void Page_Load(object sender, EventArgs e)
{
bool isUserLoggedOn = (bool)Session["IsLoggedOn"];
if(isUserLoggedOn)
{
PanelLogin.Visible = false;
}
else
{
PanelLogin.Visible = true;
}
}

when the user logins upon successful login. you should keep his username in Session as
Session["user"] = username;
Now on page Load() check if Session["user"] is null then label.text = "register"
else = label.text = "";
hope it will help.

Related

Login Redirect Issue

I want to re-direct people logging in based on their role. When I use the code below, the roles are coming up empty when debugging - I suspect because they haven't been completely logged in yet? I may be tapping into the the wrong event, can someone point me in the right direction?
<asp:Login ID="LoginUser" OnLoggedIn="Login1_LoggedIn" runat="server"
DestinationPageUrl="~/Login.aspx" EnableViewState="false"
RenderOuterTable="false">
<p>
<asp:Button ID="LoginButton" CssClass="submitButton" runat="server" Width="70"
CommandName="Login" Text="Log In"
ValidationGroup="LoginUserValidationGroup" />
</p>
</asp:login>
protected void Login1_LoggedIn(object sender, System.EventArgs e)
{
// Overrides ReturnUrl page parameter
//Response.Redirect(LoginUser.DestinationPageUrl);
if (User.IsInRole("Member"))
Response.Redirect("~/AskExpert/AskQuestion.aspx");
else if (User.IsInRole("Expert"))
Response.Redirect("~/Admin/Experts/ViewQuestions.aspx");
else if (User.IsInRole("Admin"))
Response.Redirect("~/Admin/AdminHome.aspx");
}
You could use Roles.IsUserInRole() instead. User.IsInRole reads the authentication data from the auth cookie and it seems that this data is not yet set when that event is fired.
if (Roles.IsUserInRole("Member"))
Response.Redirect("~/AskExpert/AskQuestion.aspx");
else if (Roles.IsUserInRole("Expert"))
Response.Redirect("~/Admin/Experts/ViewQuestions.aspx");
else if (Roles.IsUserInRole("Admin"))
Response.Redirect("~/Admin/AdminHome.aspx");
The downside to Roles.IsUserInRole is that if you're using a database provider, it results in a roundtrip.
I usually avoid the go and back turn of redirection, transferring the control with Server.Transfer.

Load specific part in webpage?

See below image first.
we have one sidebar navigation(ajax accordion control asp.net)
now when ever user click on link inside side bar related page(content) should display in Content goes here region.
As per given instruction entire page should not be refreshed or in other word in Back Button should not work(In Internet Explorer).
what should be the way to achieve this functionality?
what should be the best suggestion for that?
EDIT: navigation tree is inside MasterPage and Content goes region is in side content page of master page
please suggest me.....
thank you so much....
The Easiest way is to Wrap your side navigation & the Content placeholder in an UpdatePanel. Set the TreeView in the side bar as the UpdateTrigger for the update Panel. But, this approach is a little inefficient.
A slightly better way is ti just wrap the Content Placeholder in an Update Panel, along with a HiddenField in it. Upon a selection in the sidebar, update the HiddenField Value with JavaScript and then refresh the update Panel.
According to:
As per given instruction entire page should not be refreshed or in other word in Back Button should not work(In Internet Explorer).
And
sidebar tree view is in master page and Content goes here region is content page
If my understanding is correct, I think you do not need to place your TreeView control in your master page because you only want one page loading dynamically the content based on the selection of your tree view. So...Why is this important? Well if you place your tree view in your page you can use an UpdatePanel to avoid full posts.
Output of the following code
The following code covers the next points:
A TreeView control is embedded in a UserControl and placed in an ASPX page (left side)
The menu contorl exposes an event that is raised whenever the selected node changes, this event is handled in the ASPX page to dynamically load user controls depending on the user selection on the right side of the page, only one content is loaded at a time.
The controls are embedded in an UpdatePanel therefore you won't change your page and your back button in your browser won't be affected
Note: the user controls keep their state across post backs
(I'm not sure if this is the best way to do it, perhaps you could try to find a solution using only ajax, and avoid the use of the evil updata panels, but certainly this is a way to do it)
I'll try to simplify the code to reduce the size of the post, I will just post the code of one user control, the other one is exactly the same I just changed its title to difference them on the page
ASCX Menu
<asp:TreeView ID="TreeView1" runat="server" onselectednodechanged="Unnamed2_SelectedNodeChanged">
<Nodes>
<asp:TreeNode Text="link1" />
<asp:TreeNode Text="link2" />
</Nodes>
<SelectedNodeStyle Font-Bold="True" Font-Italic="True" />
</asp:TreeView>
ASCX Menu code behind
public event Action<string> MenuChanged = delegate { };
protected void Unnamed2_SelectedNodeChanged(object sender, EventArgs e)
{
this.MenuChanged(this.TreeView1.SelectedNode.Text);
}
ASPX
<asp:ScriptManager runat="server" ID="sm" />
<asp:UpdatePanel runat="server" ChildrenAsTriggers="true">
<ContentTemplate>
<asp:HiddenField runat="server" ID="currentControl" />
<table border="0" cellpadding="0" cellspacing="0" width="90%" align="center">
<tr>
<td style="width:50%; background-color: Silver">
<menu:TreeViewMenu runat="server" ID="myTreeViewMenu" OnMenuChanged="myTreeViewMenu_MenuChanged" />
</td>
<td style="width:50%; background-color: Aqua">
<p>Result:</p>
<asp:Panel runat="server" ID="myPanel">
</asp:Panel>
<asp:Label ID="lblMessage" runat="server" />
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
ASPX code behind
protected void Page_Init(object sender, EventArgs e)
{
if (this.IsPostBack)
{
var cc = this.Request.Form["currentControl"];
if (!string.IsNullOrWhiteSpace(cc))
{
var uc = this.LoadControl(this.Server.HtmlDecode(cc));
this.myPanel.Controls.Add(uc);
}
}
}
protected void myTreeViewMenu_MenuChanged(string e)
{
this.myPanel.Controls.Clear();
switch (e)
{
case "link1":
var cc1 = "~/Content1.ascx";
this.currentControl.Value = this.Server.HtmlEncode(cc1);
var uc1 = this.LoadControl(cc1);
this.myPanel.Controls.Add(uc1);
this.lblMessage.Text = "Updated from: link1";
break;
case "link2":
var cc2 = "~/Content2.ascx";
this.currentControl.Value = this.Server.HtmlEncode(cc2);
var uc2 = this.LoadControl(cc2);
this.myPanel.Controls.Add(uc2);
this.lblMessage.Text = "Updated from: link2";
break;
default:
this.lblMessage.Text = "Updated from default: " + e;
break;
}
}
ASCX
<h1>Content 1</h1>
<asp:TextBox runat="server" ID="txt" />
<asp:Button Text="Process data..." runat="server" OnClick="button_Click" />
<asp:Button Text="Just post" runat="server" />
<asp:Label ID="lblMessage" runat="server" />
ASCX Code Behind
protected void button_Click(object sender, EventArgs e)
{
this.lblMessage.Text = this.txt.Text;
}
You can simply copy-paste this code to test it yourself, this should work
Jupaol's answer works fine but 1 thing need to mention, I came across the problem after implemented Jupaol's idea, the first time I called the user control immediately after I click menu, the button with in the ascx works fine, but if I switch to 2nd one, first click of the button on the 2nd control will not fire on first click, this is because we do not have a "static" ID of the control. It took me almost 3 days to finally figure out why this is happening. so here's part of my code to make. I'm leaving this message in hope that anyone who read this afterwards will make the use of it.
if (!string.IsNullOrEmpty(controlPath))
{
PlaceHolder1.Controls.Clear();
UserControl uc = (UserControl)LoadControl(controlPath);
/**note below LastLoadedControl is anything that could
* be unique to the called control so every time when call back
* it will not confuse the back end so the first fire of eg. a button
* on that loaded control will work
*/
uc.ID = LastLoadedControl;
PlaceHolder1.Controls.Add(uc);
}
I'll also need to thank Jupaol's great contribution so that I can get my site running.

ASP.NET frameset target to new frame

I have an ASP.NET page in a frameset. I divided into 2 frames, 1.LEFTNAVI and 2.MAIN.
In the first frame (LEFTNAVI) I'm using a textbox and a button for the search engine in below tree menu. If I click the search button or menu it will display the result in the 2nd frame (MAIN) (that is, target=MAIN). Now the problem is, the application session ends, then I click the search button. It will display the login page to start the session, after login, it is displaying the LEFTNAVI frame text in MAIN frame. That is, the textbox, search button and tree menu is displayed in MAIN frame.
Below is the code I'm using in left.aspx.
<script type="text/javascript" language="javascript">
function pageSubmit()
{
var myForm = document.getElementById('form1');
myForm.target = 'main';
}
function KeyDownHandler(btn)
{
if (event.keyCode == 13)
{
event.returnValue=false;
event.cancel = true;
btn.click();
}
}
</script>
<body>
<form id="form1" method="post" runat="server">
<div id="searchFunc" runat="server">
<asp:TextBox
ID="txtSearch"
CssClass="txtbox"
onKeyDown= "KeyDownHandler(searchButt)"
runat="server"></asp:TextBox>
<asp:Button
ID="searchButt"
runat="server"
CssClass="smallbutton"
Text="Search"
onclick="searchButt_Click"
OnClientClick="pageSubmit()" />
</div>
<br />
<br />
<asp:TreeView
CssClass="treeview"
ID="tree"
runat="server"
LineImagesFolder="~/TreeLineImages"
ShowLines="True" ExpandDepth="1" >
<Nodes>
<asp:TreeNode Text="sample tree menu" Value="sam" SelectAction="Expand">
</Nodes>
</asp:TreeView>
</form>
</body>
You can use redirect url. in this case your login page should have a parameter in query string witch will demonstrate the page url that redirected to login page and sure login page should redirect to that page after successful login.
in this case login page should check for redirect url after successful login and automatically redirect to it. in your case, it will redirect to result page (not search page).
sample scenario :
private void DoLogin()
{
//write some code for user validation
if(loggedin) //login was successful
{
//redirect to page that redirected to login because of session end
var redirectUrl = Request.QueryString["redirectUrl"];
Response.Redirect(redirectUrl);
}
}
remember if you are using membership provider of asp.net it will do it for your.

ASP.Net: Ajax check for registration as a user?

I have an user registration on my site.
I want to look it cool, so my plan is, that after a textbox is left, a green or red sign right behind the textbox tell the user if e.g. the username is unused, the email-adress is unused, the password is correct entered twice and so on.
Yes, I know the validation controls, but there are only a bunch of functions, isn't it? E.g. for checking if the email-adress is unused I must check by database and so on...
Any Ideas?
I would wrap the whole thing in an update panel, this is something I do quite often...
<asp:scriptmanager runat="server" id="sm1" />
<asp:updatepanel runat="server" id="up1" updatemode="Conditional">
<contenttemplate>
<asp:textbox runat="server" id="tbUsername" autopostback="true" ontextchanged="tbUsername_TextChanged" />
<asp:customvalidator runat="server" text="Email already used" id="cusValEmail" />
<asp:textbox runat="server" id="tbPassword" />
</contenttemplate>
</asp:updatepanel>
and in the code behind
protected void tbUsername_TextChanged(object sender, EventArgs e)
{
//call DB etc and mark validator as needed
cusValEmail.IsValid = false;
}
The key is setting the textbox autopostback to true and utilising the ontextchanged event.
A simple way of doing this would be to create a controller action (if you are using MVC) or a page (if you are using regular asp/asp.net) that you post the username, e-mail address, etc to that returns a simple plain-text colour value - red or green, depending on whether all the parameters have been posted are ok. You could then apply that to the colour-style of the box. If you don't have/want that to be an https call then I probably wouldn't include the passwords in that, you ajax return code could maybe say
if (<password are equal>)
{
set style-colour to the return value
}
else
{
set to red
}
or probably, even better, something like
if (<passwords are equal>)
{
run ajax call
}
else
{
set style-colour to red
}
and the the ajax return sets the colour to the return value, that way you also save a round trip to the server if the passwords aren't equal
Any reason you want/need to do this via ajax rather than a regular postback (you could use an update panel to do a partial postback)?

multiple forms in asp.net

is it possible to display, with a click of a button an entirely different form on the same aspx page? please take note that although i have experience with vb.net, i have almost none with asp.net. thank you very much for your responses
I would use and in your code behind, load up the page and then place it in the placeHolder. And then hide the old form using javascript. The idea the other person said would also work, but I like using the placeholder, myself.
I think it's all really determinate on what you want to do with the forms and how badly you would want the code for the other form laying on the page, or not.
If I understand, what you need is, on the click event:
response.redirect "newpage.aspx"
Create each of the forms on the same page, one with visible=true and the other visible=false, and when the user clicks on the appropriate button, switch the visibilities.
<form id="Form1" runat="server" visible="true">
<div>
<asp:Button ID="Button1" runat="server" Text="Show Form 2" onclick="Button1_Click" />
</div>
</form>
<form id="Form2" runat="server" visible="false">
<div>
<asp:Button ID="Button2" runat="server" Text="Show Form 1" onclick="Button2_Click" />
</div>
</form>
And in the code behind:
protected void Button1_Click(object sender, EventArgs e)
{
this.form2.Visible = true;
this.form1.Visible = false;
}
protected void Button2_Click(object sender, EventArgs e)
{
this.form2.Visible = false;
this.form1.Visible = true;
}
Probably not the most "Ajaxy" solution, but you could use an iframe, with the src set to the forms location.
You should be aware of ASP.NET's MultiView control. It does require a postback to change views, and it is kinda heavy on the ViewState, but its an option to consider.
Well, there's several ways to go about that I suppose. Riffing off tekBlues, you can do a Server.Transfer "yourpage.aspx". You can then use the PreviousPage property to get to data from the old page.
You can use user controls and a placeholder on the main page. Of course dynamically loaded controls holds extra complexity.
You could use a MultiView control. Asp.Net will maintain all vars for you. Useful for the quick and dirty.
These are all webform solutions though. If you're looking for an AJAX solution, might need to keep on looking for answers.
It is NOT allowed to have more then 1 form runat="server" on an asp.net page. What you could do, is create 2 panels on your page, 1 with the Visible property set to false. Then when a button is clicked in the event handler you set the Visisble property to true, while setting the other 1 to false. Wrap the Panel in an UpdatePanel to get rid of the postback.
<asp:UpdatePanel><ContentTemplate>
<asp:Panel ID="pnl1" runat="server">
<asp:Button OnClick="Button_CLick" />
</asp:Panel>
<asp:Panel ID="pnl2" runat="server" Visible="false">
</asp:Panel></ContentTemplate></asp:UpdatePanel>
the code in the Button_CLick handler would then be pnl1.Visible = false; pnl2.Visible = true;
You could do it with CSS/Javascript, here is what I would do first:
1) code up two forms, place them in a separate divs
2) using CSS hide one div on page load
3) then place a button on the page, in the onlick button event unhide the second form and hide the first one.
Make sure that you only have ONE form tag, but 2 divs inside it which you will hide/unhide. Keep in Mind that that the form can only be submitted to its own page, that's asp.net.
in your HTML:
<form runat="server" id="myForm">
<div id="myForm1">
<! -- form 1 code goes here -- !>
</div>
<div id="myForm2">
<! -- form 2 code goes here -- !>
</div>
<input type="button" onclick="toggleVisibility();" />
</form>
Then in your CSS
#myForm1 {
display: none;
}
Then ToggleVisibility() will change the display attribute of divs.
Use AJAX to load the content of another page into the same page.
Use Response.Redirect or Server.Transfer to move to the next page.

Resources