Scenario:
I am doing project in C# ASP.NET 4.
I have a page of question. When somebody clicks on question (ie a Link Button) he is redirected to page where user can give answer but first he needs to login. So I put Login to Answer button that redirects user to GuestLogin.aspx with question id like this :
protected void LoginToAnswwer_Click(object sender, EventArgs e)
{
int qidrequest = int.Parse(Request.QueryString["qid"]);
Response.Redirect("~/GuestLogin.aspx?qid=" + qidrequest);
//This is working OK
}
And then when I am redirected to GuestLogin.aspx, I am putting below code in LoginButton of built in Login Control.
protected void LoginButton_Click(object sender, EventArgs e)
{
int qidrequest = int.Parse(Request.QueryString["qid"]);
Response.Redirect("QDisplay.aspx?qid=" + qidrequest);
}
Which is not working.
Question:
How to pass querystring with login button of built login control in asp.net 4 ?
You could pass a return URL to the login page, like this:
Response.Redirect(String.Format("/auth/login.aspx?return={0}", Server.UrlEncode(Request.Url.AbsoluteUri)));
In the login page, after authenticating the user:
Response.Redirect(Request.QueryString["return"]);
Pass Parameters from One Page to Another Page using QueryString :
//Set the Querystring parameters
Note: Maximum length of the
string that can be passed through QueryString is 255.
string URL =“QueryString.aspx?Name=” + txtFirstName.Text + “&Address=” + txtAddress.Text + “&City=” + txtCity.Text ;
//After Setting the Querystring Paramter values Use Response.Redirect to navigate the page
Response.Redirect(URL);
In the Page Load Event of the Navigated
Page,You can access the querystring parameter values like below :
lblName.Text = Request.QueryString["Name"].ToString();
lblAddress.Text = Request.QueryString["Address"].ToString();
lblCity.Text= Request.QueryString["City"].ToString();
That's how you have to use QueryString for passing parameters
Related
I'm extremely new to ASP.NET and came across a problem I have yet to figure out. On my Default.aspx page, I have a place where users can signup. This just takes to fields - Email and Password. When the submit button is clicked, they are taking to Signup.aspx, which shows a bigger signup form with fields for username, email, password, confirm password, etc. I would like to auto fill my email and password textboxes with those of the Default.aspx page that the user has entered. Is this possible? I'm using Microsoft Visual Web Developer 2010 Express.
There are multiple ways to do that.
One way is to use querystring to navigate to like :
http://example.com/Signup.aspx?email=value1&password=value2
and get value on Signup.aspx Page_Load event like :
String email = Request.QueryString["email"];
String password = Request.QueryString["password"];
and assign to your text box controls like:
txtEmail.text =email;
txtPassword=password;
But posting password as clear text in query string is not good practice.
Other way is to get HTTP POST information from the source page:
In the source page, include a form element that contains HTML elements (such as input or textarea) or ASP.NET server controls (such as TextBox or DropDownList controls) that post values when the form is submitted.
In the target page, read the Form collection, which returns a dictionary of name/value pairs, one pair for each posted value. e.g.
//
void Page_Load(object sender, EventArgs e)
{
System.Text.StringBuilder displayValues =
new System.Text.StringBuilder();
System.Collections.Specialized.NameValueCollection
postedValues = Request.Form;
String nextKey;
for(int i = 0; i < postedValues.AllKeys.Length; i++)
{
nextKey = postedValues.AllKeys[i];
if(nextKey.Substring(0, 2) != "__")
{
displayValues.Append("<br>");
displayValues.Append(nextKey);
displayValues.Append(" = ");
displayValues.Append(postedValues[i]);
}
}
Label1.Text = displayValues.ToString();
}
Best & easiest I think is to use Session:
on Submitbutton_click event of Default.aspx, save values to Session like:
Session["Email"] = txtEmail.text;
Session["Password"]=txtPassword.text;
and retrieve values on Signup.aspx Page_load event like:
string email = (string)(Session["Email"]);
string password = (string)(Session["Password"]);
& assign to your control/textbox like:
txtEmail.text =email;
txtPassword=password;
There are more ways too to retrieve value from previous page like PreviousPage.FindControl("txtEmail") but I never like them.
I want to ask how to pass a variable from a page to another page.
example.
in (page1.aspx.cs) there is button click and textbox
protected void Button1_Click(object sender, EventArgs e)
{
textbox1.text = ;
}
in (page2.aspx.cs)
A = "hello"
// A is variable that can be change, A variable is coming from microC
What I want is show "hello" from page2 in textbox1.text when I click button1 in page1.aspx
You can pass the value as a querystring parameter.
So if you are using Response.Redirect you could do something like
protected void Button1_Click(object sender, EventArgs e){
Response.Redirect("Page2.aspx?value=" + taxtbox1.text);
}
On Page 2 you can get the value using Request["value"].ToString()
Notice that the querystring parameter name is what you request. So if you have ?something=else you will Request["something"]
One way is to place the value into some form of temporary storage: Cookie, Session, etc. And then redirect.
Another would be to redirect with a query string value. It really depends on your situation.
I'd recommend setting a session if this is necessary.
Session["sessionname"] = "";
Though it isn't ideal, is it possible to have everything on page1? You can switch with a panel control.
Without a Postback it is not possible!
With a Postback, yes it is (see Cross Page Postback). Also see in the link what you can have access to! (Access possibilities are page controls & public members).
Other options, Session variables, cookies, query string, etc!
u can use one of this ways:
1- Query string
page.aspx?ID=111&&Name=ahmed
2- Session
Session["session1"] = "your value";
3- Public property
public String prop1
{
get
{
return txt_Name.Text;
}
}
4- Controls Data
5- HttpPost
Hi I have problem with store user name in Session. On log on page I store user name to session. User input credentials on logon page and then is redirect on default page. I need in class Default access to variable store in session.
Logon.aspx
<script runat="server">
void Login_Click(object sender, EventArgs e)
{
Session["user"] = tbUserName.Text;
//You can redirect now.
Response.Redirect(FormsAuthentication.GetRedirectUrl(tbUserName.Text,
false));
}
</script>
secod main page is here:
Default.aspx-Default.aspx.cs
public partial class Default : Page,
IHttpHandler, System.Web.SessionState.IRequiresSessionState
{
string userName = (string) (Session["user"]);
}
but result is that userName is empty.
Web config is here:
<sessionState cookieless="true" regenerateExpiredSessionId="true" />
Thank you for advice.
If the snippet is on the module level (as alluded to by Bala R in the comments) the session state has probably not been set yet. Try getting it in a method that is part of the page life cycle (like page_load, etc.).
Why not get it directly from HttpContext HttpContext.Current.User.Identity.Name
Edit: I guess you are trying to get it at page level instead of in page_load or another place. That's why you are not getting a session value.
I hope below will work for you
protected void Page_Load(object sender, EventArgs e)
{
string userName = (string) (Session["user"]);
}
Update: This is incorrect.
You're losing the (cookieless) session when you redirect. Cookieless sessions are maintained in the URL, and are lost when you explicitly redirect, so there is nothing in the session on your second page.
So I have an asp:Login field on my login page.
However, I want to use a path for the create account url and the forgot password url. So I have to do it in Page_Load or maybe Page_Init. Regardless, neither option works, it simply refuses to modify the login form.
protected void Page_Load(object sender, EventArgs e)
{
string accountpath = Request.Url.AbsoluteUri + "/user/RequestAccount.aspx";
string forgotpath = Request.Url.AbsoluteUri + "/user/ForgotPassword.aspx";
lgnMain.CreateUserUrl = accountpath;
lgnMain.PasswordRecoveryUrl = forgotpath;
lgnMain.InstructionText = "test";
lgnMain.Focus();
}
protected void Page_Init(object sender, EventArgs e)
{
string accountpath = Request.Url.AbsoluteUri + "/user/RequestAccount.aspx";
string forgotpath = Request.Url.AbsoluteUri + "/user/ForgotPassword.aspx";
lgnMain.CreateUserUrl = accountpath;
lgnMain.UserName = "test";
lgnMain.InstructionText = "test";
lgnMain.PasswordRecoveryUrl = forgotpath;
}
The CreateUserUrl and the PasswordRecoveryUrl are ignored if you haven't set the CreateUserText and PasswordRecoveryText properties respectively. Since the Text properties probably don't need to be dynamic, just set them in the ASPX (although you could still set them in the code behind if required), and then the dynamic setting of the URL properties (in the Page_Load event) should work without problem.
Documentation here: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.login_members(v=vs.85).aspx
From the Documentation above:
If the CreateUserText property is
empty, the link to the registration
page is unavailable to the user.
If the PasswordRecoveryText property
is empty, the link to the password
recovery page is not available to the
user.
have you tried setting it in the markup?
<asp:Login id="lgnMain" runat="server"
CreateUserText="Register"
CreateUserUrl="~/user/RequestAccount.aspx"
PasswordRecoveryText = "Forgot Password"
PasswordRecoveryUrl = "~/user/ForgotPassword.aspx" >
</asp:Login>
I have a page www.senderdomain.com/sender.aspx, from which i need to write a string to another page in other domain www.receiverdomain.com/receiver.aspx
In sender.aspx i have written
Response.Write("Hello");
Response.Redirect(Request.UrlReferrer.ToString());
It gets redirected to respective receiver.aspx page, but I am not sure how to get the text "Hello" in receiver.aspx page. Can any pl help on this?
It seems you have a value on Sender.aspx that you need to display in receiver.aspx. This is how you can do it.
//On Page_Load of sender.aspx
Session["fromSender"] = "Hello";
Respone.Redirect("receiver.aspx");
Response.End();
//On Page_Load of receiver.aspx
if(!string.IsNullOrEmpty(Session["fromSender"].ToString()))
Response.Write(Session["fromSender"].ToString());
EDIT
In case of change in domain, immediate easy way is to pass the value in query-string.
//On Page_Load of sender.aspx
Response.Redirect("http://www.receiverdomain.com/receiver.aspx?fromSender=Hello");
Response.End();
//On Page_Load of receiver.aspx
if(!string.IsNullOrEmpty(Request.QueryString["fromSender"].ToString()))
Response.Write(Request.QueryString["fromSender"].ToString());
You may observe that the code pattern remains the same and container that is used to transfer the value changes from Session to QueryString.
EDIT2
If security is a concern with you in this case and you don't wish to expose the value ["Hello"], then here comes another way that can help you. In this solution we will first redirect the page to receiver and then from receiver it shall ask for the value to sender. So first we'll write the code for receiver.
//On Page_Load of receiver.aspx
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Remember to use System.Net namespace
HttpWebRequest requestToSender = (HttpWebRequest)WebRequest.Create("http://www.senderdomain.com/sender.aspx?cmd=getvalue");
HttpWebResponse responseFromSender = (HttpWebResponse)requestToSender.GetResponse();
string fromSender = string.Empty;
//Remember to use System.IO namespace
using (StreamReader responseReader = new StreamReader(responseFromSender.GetResponseStream()))
{
fromSender = responseReader.ReadToEnd();
}
Response.Write(fromSender);
Response.End();
}
}
And in the sender.aspx
//On Page_Load of sender.aspx
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (!string.IsNullOrEmpty(Request.QueryString["cmd"].ToString()))
{
string cmd = Request.QueryString["cmd"].ToString();
if (cmd.Equals("getvalue", StringComparison.OrdinalIgnoreCase))
{
Response.Clear();
Response.Write("Hello");
Response.End();
}
}
Response.Redirect("http://www.receiverdomain.com/receiver.aspx");
Response.End();
}
}
You need to pass the value in the url or post it in a cross page postback.
For secure cross domain communication, take a look at SAML (Security Assertion Markup Language). It is a standard way of passing information securely across domain boundaries. It is most often used in Single Sign On scenarios, but it can be used to pass data securely. Are you using certificates? What type of encryption are you using?
Another option would be to save state to a database or filesystem that is accessible to both domains.
pass data in query string because can not do like this
for example
Response.Redirect(Request.UrlReferrer.ToString() + "?mytext=hello");
And in receiver page access querystring data, will resolve your issue.
use private algorithm like
string message = "hello";
add 1 to each char so that hello become ifmmp
and on receiver side -1 from each char so it will be hello
The Response.Redirect method will scrap everything that you have written to the page, and replace it with a redirection page, so you can't send any content along with the redirect.
The only option to send data along in a redirect (that works between differnt domains and different servers) is to put it in the URL itself. Example:
string message = "Hello";
Response.Redirect(Request.UrlReferrer.ToString() + "?msg=" + Server.UrlEncode(message));
Another option is to output a page containing a form that is automatically posted to the destination:
string message = "Hello";
Response.Write(
"<html>" +
"<head><title>Redirect</title></head>" +
"<body onload=\"document.forms[0].submit();\">" +
"<form action=\"" + Server.HtmlEncode(Request.UrlReferrer.ToString()) + "\" method=\"post\">" +
"<input type=\"hidden\" name=\"msg\" value=\"" + Server.HtmlEncode(message) + "\">" +
"</form>" +
"</body>" +
"</html>"
);
Response.End();
You can use Request.Form["msg"] on the recieving page to get the value.
Don't use the built-in URL encode, if you want to avoid all sorts of problems later.
String UrlEncode(String value)
{
StringBuilder result = new StringBuilder();
foreach (char symbol in value)
{
if ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~".IndexOf(symbol) != -1) result.Append(symbol);
else result.Append("%u" + String.Format("{0:X4}", (int)symbol));
}
return result.ToString();
}
The above supports unicode, and pretty much everything.