I am trying to add a condition for a hyperlink that I have in my page.
Instead of just using a particular link like: Tutorial I want to display different pages for different users. For example, if the user is logged in as Admin, they will be presented with different link than regular users.
I have modified my hyperlink as: <a onclick="displayTutorial_Click">Tutorial</a>
and added this code:
protected void displayTutorial_Click(object sender, EventArgs e)
{
// figure out user information
userinfo = (UserInfo)Session["UserInfo"];
if (userinfo.user == "Admin")
System.Diagnostics.Process.Start("help/AdminTutorial.html");
else
System.Diagnostics.Process.Start("help/UserTutorial.html");
}
But this didn't work. Can anyone please help me to figure out how I can make the Tutorial link work properly? Thank you a lot in advance!!!
The onclick attribute on your anchor tag is going to call a client-side function. (This is what you would use if you wanted to call a javascript function when the link is clicked.)
What you want is a server-side control, like the LinkButton:
<asp:LinkButton ID="lnkTutorial" runat="server" Text="Tutorial" OnClick="displayTutorial_Click"/>
This has an OnClick attribute that will call the method in your code behind.
Looking further into your code, it looks like you're just trying to open a different tutorial based on access level of the user. You don't need an event handler for this at all. A far better approach would be to just set the end point of your LinkButton control in the code behind.
protected void Page_Load(object sender, EventArgs e)
{
userinfo = (UserInfo)Session["UserInfo"];
if (userinfo.user == "Admin")
{
lnkTutorial.PostBackUrl = "help/AdminTutorial.html";
}
else
{
lnkTutorial.PostBackUrl = "help/UserTutorial.html";
}
}
Really, it would be best to check that you actually have a user first.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["UserInfo"] != null && ((UserInfo)Session["UserInfo"]).user == "Admin")
{
lnkTutorial.PostBackUrl = "help/AdminTutorial.html";
}
else
{
lnkTutorial.PostBackUrl = "help/UserTutorial.html";
}
}
Wow, you have a huge misunderstanding how asp.net works.
This line of code
System.Diagnostics.Process.Start("help/AdminTutorial.html");
Will not redirect a admin user to a new site, but start a new process on the server (usually a browser, IE) and load the site. That is for sure not what you want.
A very easy solution would be to change the href attribute of the link in you page_load method.
Your aspx code:
Tutorial
Your codebehind / cs code of page_load:
...
if (userinfo.user == "Admin")
{
myLink.Attributes["href"] = "help/AdminTutorial.html";
}
else
{
myLink.Attributes["href"] = "help/otherSite.html";
}
...
Don't forget to check the Admin rights again on "AdminTutorial.html" to "prevent" hacking.
this may help you.
In .cs page,
//Declare a string
public string usertypeurl = "";
//check who is the user
//place your code to check who is the user
//if it is admin
usertypeurl = "help/AdminTutorial.html";
//if it is other
usertypeurl = "help/UserTutorial.html";
In .aspx age pass this variabe
<a href='<%=usertypeurl%>'>Tutorial</a>
Related
I'm wondering what is my issue on passing a variable from page to page using asp.net session.
I've stripped the code down to just one text box to see whats going on. I'm just trying to take the value of a text box and display it on a confirmation page. When the button is clicked it transfers me to the second page but there label is blank. Yes my post back url is pointing to the second page.
Here is the button click:
protected void submit_Click(object sender, EventArgs e)
{
string name = txtFirstName.Text.Trim();
Session["name"] = name;
}
Here is the page load of the second page:
protected void Page_Load(object sender, EventArgs e)
{
lblName.Text = (string)(Session["name"]);
}
Unless I've been looking at this to long and missed something. I've already read "How to: Read Values from Session State" from MSDN.
You say that you've set the PostBackUrl to your second page. If you're going to do it that way, you need to use Page.PreviousPage to get access to your textbox. But this is the easiest way:
Firstly, leave the PostBackUrl alone. Setting the PostBackUrl to your second page means that you're telling the SECOND PAGE to handle your button click, not the first page. Hence, your session variable never gets set, and is null when you try to pull it.
This should work for ya.
And yes, you can also do this with a QueryString, but if its something that you don't want the user to see/edit, then a Session variable is better.
protected void submit_Click(object sender, EventArgs e)
{
string name = txtFirstName.Text.Trim();
Session["name"] = name;
Response.Redirect("PageTwo.aspx");
}
Then in the second page (You don't REALLY need the ToString()):
protected void Page_Load(object sender, EventArgs e)
{
if (Session["name"] != null)
{
lblName.Text = Session["name"].ToString();
}
}
EDIT -- Make sure that your button click actually gets fired. Someone can correct me wrong on this, as I do most of my work in VB.NET, not C#. But if you don't specify the OnClick value, your function won't get called.
<asp:Button ID="Button1" runat="server" Text="Click Me!" OnClick="submit_Click" />
The code you have posted looks fine, so your problem is probably with setup.
Check this link ASP.NET Session State Overview and pay particular attention to the sections on Cookieless SessionIDs and Configuring Session State.
I don't think you added the session. This is how I have done mine.
First Page
protected void btnView_Click(object sender, EventArgs e)
{
foreach (ListItem li in lbxCheckDates.Items)
{
if (li.Selected == true)
{
lblMessage.Text = "";
string checkDate = lbxCheckDates.SelectedItem.Text;
Session.Add("CheckDates", checkDate);
Page.ClientScript.RegisterStartupScript(
this.GetType(), "OpenWindow", "window.open('Paystub.aspx','_newtab');", true);
}
}
}
Second Page
protected void Page_Load(object sender, EventArgs e)
{
string checkDate = (string)(Session["CheckDates"]);
//I use checkDate in sql to populate a report viewer
}
So with yours, I think you need..
protected void submit_Click(object sender, EventArgs e)
{
string name = txtFirstName.Text.Trim();
Session.Add("Name", name);
}
I think what you have in the second page should work, but if it doesn't, add ToString() to it like..
lblName.Text = (string)(Session["name"]).ToString();
Let me know if this helps!
Are you doing a redirect after setting the session variable on the first page, if so you it will not work correctly (unless you know the trick). Checkout this article on making it work. Basically, the way to make this work is to the overload redirect method.
Response.Redirect("~/newpage.aspx", false);
The false parameter prevents .net from terminate processing on the existing page (that actually writes out the session state)
For Second Page
protected void Page_Load(object sender, EventArgs e)
{
if (Session["value"] != null)
{
Label1.Text = Session["value"].ToString();
}
else
{
Label1.Text = "Sorry,Please enter the value ";
}
}
You can use Server.Transfer() instead of Response.Redirect()
For first page, use this:
protected void Button1_Click(object sender, EventArgs e)
{
string value = TextBox1.Text;
Session["value"] = value;
Response.Redirect("~/Sessionpage.aspx");
}
i use asp login control in web application (ASP.NET 4). if user in admin role i want redirect to admin page.
i use this code, but not working:
protected void baseLogin1_LoggingIn(object sender, LoginCancelEventArgs e)
{
if (Page.User.Identity.IsAuthenticated && Roles.IsUserInRole(Page.User.Identity.Name, "Admin"))
{
Page.Response.Redirect("admin/Default.aspx");
}
}
please help me.
LoggingInEvent is raised before the user is authenticated. So the first part of your condition is always false. Move you logics under LoggedIn event.
Try this one:
protected void baseLogin1_LoggedIn(object sender, EventArgs e)
{
if (Context.User.Identity.IsAuthenticated && Context.User.IsInRole("Admin"))
{
Context.Response.Redirect("admin/Default.aspx");
}
}
Use the LoggedIn event: Event description is here
You should really be using Server.Transfer("~/admin/Default.aspx"); as it is a little more efficient (less round trips).
If the page needs to preserve the query string for a bookmark or it is important to preseve the correct URL in the browser then Response.Redirect() is needed but be aware of the extra bandwidth cost.
I think my tittle is inaccurate.
When a user clicks on a button I need it to do this:
Response.Redirect("Login.aspx?userid=XX");
How can I get the "userid?" from ?userid. so I can show a page. Like doing "?page=3" and show page 3, in the same page or something.
The Button code is: (just if you need it)
protected void LoginButton_Click(object sender, EventArgs e)
{
Response.Redirect("Login.aspx");
}
Thanks a lot! Sorry if I didn't ask it good, and sorry for the bad English.
Use Request.QueryString:
First Page Sends them another page with their user id in the url:
Response.Redirect("AfterLogIn.aspx?userid=23");
You then Read it using the below code:
var g = Request.QueryString["userid"] //this value should be 23 now
You could then use this g variable to do any amount of custom things (Hide panels, show controls, etc.)
You can do something like this
protected void LoginButton_Click(object sender, EventArgs e)
{
var id = // whatever userid
Response.Redirect("Login.aspx?userid="+ id);
}
and in the pageload of Login page
var userid = Request.QueryString["userid"];
ASP.NET State Management will explain further.
Hope this helps
I have a problem with using session variable in the page_load. I have a page (members.aspx) which is a members area.
If the user isn't logged in, it will display a form asking them to login. The form submits their details, checks if ok then sets session variables if OK. It then reloads the page.
So if the user has authenticated correctly, it sets Session["memberLoggedIn"] = true.
My page_load function then looks like this
protected void Page_Load(object sender, EventArgs e)
{
if (Convert.ToBoolean(Session["memberLoggedIn"]) == true) {
Response.Write("OK");
}
}
There is more code, but essentially, the "OK" should be written. However, it doesn't appear. Even though the session IS set. If I go to the page directly it will then show. It's just for the reloading of the members page from the initial login which stops it.
any ideas?!
======================
the code to set the session is
if (logindetails.Count > 0) {
System.Data.DataRow details = logindetails[0];
Session["memberLoggedIn"] = true;
}
I then just check if (Convert.ToBoolean(Session["memberLoggedIn"]) == true) on all my pages. To be honest it doesn't seem that reliable and I Think sometimes I need to understand the order in which pages are loaded as when I destroy the session on the log out page, some parts still show the logged in features! (but that's another story....)
try this
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
var user = HttpContext.Current.User;
if(user.Identity.IsAuthenticated)
{
Session["memberLoggedIn"] = true;
Print();
}
}
}
public void Print()
{
if (Convert.ToBoolean(Session["memberLoggedIn"]) == true)
{
Response.Write("ok");
}
}
This sounds like when you log in you are choosing whether to write "OK" before you have processed the login. In terms of the page's pipeline page_load is before your event handler that you are likely processing the login.
You have various options, the simplest of which could be to move this particular logic to Page_PreRender (if it makes sense to) as at this point your session variable will have been set.
OK, here's the thing... You fetch the user's IP address and based on his/her country you redirect the user to a specific webpage. Now, how do you change the master page dynamically? This is how I am redirecting the user :-
Geolocation error with IP address 127.0.0.1
It's not like the user clicks some button or something and you then change the master page. I want it changed when the user is redirected, so how exactly do I go about it?
public partial class testClass: System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
if (redirected to site1)
{
Use this master page1
}
else
if (redirected to site2)
{
Use this master page2
}
}
}
So how do I check what SITE the user has been redirected to? Also HOW to apply the specific master page now that the user has been redirected?
I just need an idea how to go about it.
[EDIT] please check the code block below. How do I fetch the URL that the user has been redirected to? I actually need just the "iso3166TwoLetterCode" variable's value (see the link to my earlier question, please) and based on that will be changing the master page. I can't figure out how to fetch that value or even use that class (that's got this variable) in my testClass.
protected void Page_PreInit(object sender, EventArgs e)
{
if (user Has been redirected to www.site.in )
{
this.MasterPageFile = "master1.master";
}
if (user Has been redirected to www.site.fr )
{
this.MasterPageFile = "master2.master";
}
}
To find out the country two letter code, do what this sample code from http://ipaddressextensions.codeplex.com/ does:
using System.Net;
using WorldDomination.Net;
string userHostIpAddress = "203.1.2.3";
IPAddress ipAddress;
if (IPAddress.TryParse(userHostIpAddress, out ipAddress))
{
string country = ipAddress.Country(); // return value: UNITED STATES
string iso3166TwoLetterCode = ipAddress.Iso3166TwoLetterCode(); // return value: US
}
you can then try something like this to change the master:
protected void Page_PreInit(object sender, EventArgs e)
{
this.MasterPageFile = "NewMasterSite.master";
}
It sounds like you're not redirecting to another site, just sending them to a page with a querystring like "language=en". If so, then you need to get it with Request.QueryString and append it to a base master page name.