redirecting pages using session - asp.net

i'm new to ASP.NET,so plz b patient :D
i want to redirect one of my pages to the other one,and i keep the username!
i tried to use session.add and session[],but when i want to insert the username inside the brackets,it says use must int!!!but i thought i should use session["username"]
i used another way(request.querystring[]),but both have problems
here is my code
//first solution
string username="asal";
session.Add(username,username);
Response.Redirect("~/Doctor/DoctorsMainPage.aspx");
//in the other page
Label1.Text= Session["username"].ToString();//this one says use int?!
//i used this one instead of it
Label1.Text= Session[0].ToString();//with this one i get the username in other page,but one i want to pass another string like "id" with session,I can not!
//the second solution
string username="asal";
Response.Redirect("~/Doctor/DoctorsMainPage.aspx?username");
Label1.Text = Request.QueryString["username"];//this one redirect to doctors main page but set the value of username to "" !

session.Add(string, string) where the first string is the name of the variable and the second is the value.
You are adding the value twice.
//first solution
string username="asal";
session.Add("username",username); <-- this is your problem
Response.Redirect("~/Doctor/DoctorsMainPage.aspx");
//in the other page
Label1.Text= Session["username"].ToString();
Now, as for
//the second solution
string username="asal";
Response.Redirect("~/Doctor/DoctorsMainPage.aspx?username");
Label1.Text = Request.QueryString["username"];//this one redirect to doctors main page but set the value of username to "" !
In this case you're creating a url "~/Doctor/DoctorsMainPage.aspx?username"
Ok - so what is username? The code is looking for a param in the query string named username but it's not finding a value.
You need:
Response.Redirect("~/Doctor/DoctorsMainPage.aspx?username="+username);
That will give you "~/Doctor/DoctorsMainPage.aspx?username=asal"

string username = "asal";
Session["username"] = username;
Response.Redirect("~/Doctor/DoctorsMainPage.aspx");
//Other page
Label1.Text = Session["username"].ToString().Trim();

You have to add the session like..
session.Add("username",username); instead session.Add(username,username);
And then you can access the value like..Label1.Text= (String)Session["username"];
Check out this article related to the session State ASP.NET Session State Overview that will help you to understand Session State management.
Seconly querystring should be like, as you have not passing your string parameter and it should be like...
Response.Redirect("~/Doctor/DoctorsMainPage.aspx?username=" + username);

Related

Returning a value from a page

How is it possible to return a value in an ASP.NET web page? I need to return the value "1". I'm not sure how to do that. Is it as simple as writing 1 in the content of the .aspx file, or do I need to do anything else?
That's the request that is given:
GET /kartclient/kartlogin.aspx HTTP/1.1. Accept: text/*
Since kartlogin.aspx seems to be a user-login page, then are you interested in passing userID + password to another page?
Still not sure what you are trying to achieve, but if its only passing data from one page to another, there are many ways, here are some quick ones you can try:
On kartlogin.aspx:
1. Query String Method Send/Post Value:
string name="xyz";
Response.Redirect("Page2.aspx?name= "+name);
2. Cookie Method Send/Post Value:
HttpCookie myCookie = new HttpCookie("name");
myCookie.Value="xyz";
Response.Cookies.Add(myCookie);
3. Session Method Save Value:
Session["name"] = "xyz";
On Page2.aspx:
1. Query String Method Get Value:
string name = Response.QueryString.GetValue(" name ");
Response.Write(name);
2. Cookie Method Get Value:
string name = Request.Cookies('name');
Response.Write(name);
3. Session Method Get Value:
string name = Session["name"].ToString();
Response.Write(name);
You should take a look at:
How to: Pass Values Between ASP.NET Web Pages
Stackoverflow: How can I pass values from one form to another in Asp.net
Stackoverflow: When to use Request.Cookies over Response.Cookies?
Eight Different Ways to Transfer Data from One Page to Another Page

Remove the domain name from User.Identity.Name

I have he following method inside my action method:-
repository.InsertOrUpdateRack(rj.Rack, User.Identity.Name, assetid);
But the user name generated from User.Identity.Name will prefix the username with the domain name as follow:-
DOMAINNAME\username
So is there a way to force the User.Identity.Name to retrieve the username only?
Thanks.
The domain forms part of the username so I don't think any of the methods/properties return what you need. Can you not just do:
var userName = User.Identity.Name.Split('\\')[1];
Not ideal but simple enough. If you want to keep it nicely hidden away you could create an extension method on IIdentity.
The VB equivalent is (where UserWindowsName could be a variable or control used to display the Windows User Name):
Dim userName As WindowsIdentity = HttpContext.Current.Request.LogonUserIdentity
UserWindowsName = userName.Name.Split("\"c)(1)
var name = Regex.Replace(HttpContext.User.Identity.Name, #"^.*\", "");

Http.Page.Request[" "] not returning correct values

Situation:-
There is a Home.aspx page, which can be opened by a unique user ("userName" variable).
This page has a popup window control name 'alertWindow'.
In the pageLoad event of Home.aspx.cs, Welcome.aspx page is opened in the 'alertWindow' using NavigateUrl property.
The querystring passed to Welcome.aspx page contains a parameter "UserName" and this parameter is set to the logged in user's name ("userName" variable).
Now when the code execution comes to Welcome.aspx.cs page, "Request["UserName"]" is used to get\retrieve the current "userName" paramerter existing in the query string.
Issue:-
When a logged-in user's name has space or other non-usual characters, then "Request["UserName"].ToString()" doesn't retrieve the actual and correct value.
For Ex. if the logged in "userName" = "A&T Telecom", then "Request["UserName"].ToString() retrieves only "A" and nothing else.
But if the userName string is a proper value like "micheal", then "Request["UserName"].ToString() retrieves only "Micheal" correctly
Requirement:-
Please provide a way so that I get the correct value from Request["UserName"] for any kind of "userName" string value.
Home.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (user is valid)
alertWindow.NavigateUrl = "Welcome.aspx?userName=" + currentUser.ToString();
}
Welcome.aspx.cs:-
currentUserName = Request["userName"].ToString();
This is logical because you do not Encode your url. Try this:
alertWindow.NavigateUrl = "Welcome.aspx?userName=" + Server.UrlEncode(currentUser.ToString());
To say few more, they are some special characters that used on the URL, like the
: / # ? & # % + (and the space).
All that characters must be encode to a different format, so the url will not break, the UrlEncode do exactly that.
Two notes.
I select the Server to call the UrlEncode because is not depend from the Request, and you can use it inside a thread, or any function that is not called from the Page.
The Request.QueryString make UrlDecode when you use it. To get the encode url you call the Request.RawUrl
You cannot add white spaces within your url, it needs encoding so :
//uses HttpUtility.UrlEncode internally
Server.UrlEncode("something with spaces");
or
HttpUtility.UrlEncode("something with spaces");

Asp.net pass value from txtbox to an another page

This the end of my code
...
If lblErrMsg.Text = "" Then
Response.Redirect("UserPage.aspx")
End If
I want to pass the value of txtUser(I create It in the current page...) to the UserPage.aspx.
Thank's for helping me ...
This is in VB.net not in c# Please
C# Version
1) Use querystring
Response.Redirect("user.aspx?val="+txtBox.Text);
and in userp.aspx.cs,
string strVal=Request.QueryString["val"];
2)Use Session
Setting session in first page before redirecting
Session["val]=txtBox.Text;
Response.Redirect("user.aspx");
and in user.aspx.cs
String strVal=(string) Session["val"];
EDIT :VB.NET VERSION
1) Use Querystring
Response.Redirect("user.aspx?val=" + txtBox.Text)
and in user.aspx.vb
Dim strVal As String = Request.QueryString("val")
2)Use Session
Setting Session in firstpage
Session("val")=txtBox.Text
Response.Redirect("user.aspx")
and in user.aspx.vb.
Dim strVal As String = DirectCast(Session("val"), String)
You can pass it in the query string, like this:
Response.Redirect("UserPage.aspx?user=" + HttpUtility.UrlEncode(txtUser.Text));
And then retrieve it via:
string user = Request.QueryString["user"];
If you're worried about users messing with a query string (be sure to validate it), you could also store a Session variable before doing the redirect.
warning: this is a gross but easy solution
Session("myTextbox")= txtUser.Text
this will persist the value so on the page_load of the next page you can say
txtUser.Text=Session("myTextBox")
What are you passing form page to page? Is it a list of things. You could have an object with different properties and could then pass it through a session. If you have multiple pages I would suggest doing this if you could end up reusing it else where. Passing it through the url, you would then need to validate it, because if someone types the url with the correct information or something that is being directly input into a database they could cause problems and/or unexpected results.

Create our own login functionality in asp.net without using default logincontrol of ASP.NET

How to Create a Login, Signup and after user Login then loggedin username will be dispalyed in every page using Label with out using login control and create userwizard
I have following Field in My Table1
ID Username Email id Password
1 dobriyal dd#d.com ssssss
2 manish tt#d.com ttreter
i want to create login in sumit.aspx page using Textbox1 and textbox2 and button ...when user eneter emailid in textbox1 and password in textbox2 then if userfind in database according to the emailid and password entered in textbox1 and textbox2 .... then loggedin username will be displayed in label1 of each page ...where i have label 1 on page ///
means .... if i have label1 on Default.aspx, myname.aspx, defaul2.aspx then in each page the label1 text would be loggedin username .....till they loggedit its session ...
How to do it using Vb.NET
Remember I dont wanna use default login & createuserwizard, login status and login name control of ASp.NET ...
Answer of your question is very broad. So instead of code i am giving you the algorithm.
1. Create a method that will check the supplied user name and password in your data layer file.
E.g. bool IsAuthenticatedUser(). Inside this method run Command.ExecuteScalar. Here is query "
Declare #Count =(Select Count(*) From Login
Where UserName = #UserNAme and Password = #Password)
Select #Count;
-- Assuming u r using Sql Server 2008
2. Now in your IsAuthenticated Method check if the returned value is one then return true else false. Something like this
int count = (int)command.ExecuteScalar();
If (count ==1)
{
return true;
}
return false;
3. On the UI check the value returned by the method. If its true redirect the user to its page. And set session. For displaying name email id on page,
After the success of IsAuthenticated method, Create another method that will select your desired entities from database and fill it in datatable.
Something like this
If(IsAuthenticatedUser(username, password))
{
Datatable dt = GetUserDetails(username,password);
If(dt!=null)
{
if(dt.rows.count >0)
{
// here there is only one row so you can use index [0] also
foreach(DataRow dr in dt.rows)
{
Session["UserName"] = dr["UserName"].tostring();
Session["Email"] = dr["Email"].tostring();
}
}
}
Now on the desired page check if the both sessions are not null , then set the value at desired label.
If (Session["UserName"]!=null && Session["Email"]!=null)
{
lblUserName.Text = "Welcome " + Session["UserName"].ToString();
lblEmail.Text = Session["Email"].tostring();
}
**Here userName and password parameter will be the value passed from the textbox.
string username = txtUserName.text.trim();
string password = txtPassword.text.trim();
Also you to put validations before accepting input from users, as this may result in sql injection and exposing of your entire database. but for home purpose you can do this.**
See Update:
For displaying name on every page Create a master page and add the two labels on that. For adding master page , from context menu Add New Item -> MasterPage. Now in source view add table as per your need. Also there is ContentPlaceholder , do not add inside that tag. That is the space to display the other child pages. in the master page load event use the label = session code to set the name. Also there add a link button , in its click event use
Session.Abandon();
Response.Redirect("~/Login.aspx?Logout=1");
-> i have added a new thing ?Logout called query string , used for passing values from one page to another. Here i am using Login =1 that means I can know ia m on login page because i logged out myself.

Resources