It's the first time I'm passing variables between two pages in my asp.net project.
It works, but I'm wondering if it is a good way to do it? Is it secure? Is there a better way?
The reason why I ask is that I've have learned never to use concatenation in sql, but instead use parameters (which I always do from now on). Is there a similar risk in this case?
In web page1:
protected void Button1_Click(object sender, EventArgs e)
{
string email = txtEmail.Text;
string date = txtDate.Text;
string time = txtTime.Text;
string name = txtName.Text;
string url = "~/change.aspx?newemail="+mail+"&newdate="+date+"&newtime="+time+"&newname="+name+"";
Response.Redirect(url);
}
In web page2:
protected void Page_Load(object sender, EventArgs e)
{
String email = Request.QueryString["newemail"];
String date = Request.QueryString["newdate"];
String time = Request.QueryString["newtime"];
String name = Request.QueryString["newname];
TextBox1.Text = email;
TextBox2.Text = date;
TextBox3.Text = time;
TextBox4.Text = name;
}
if it is a good way to do it?
Not really. You need to url encode the values because if they contain special characters the receiving page will not parse them correctly:
string url = "~/change.aspx?" +
"newemail=" + HttpUtility.UrlEncode(mail) +
"&newdate=" + HttpUtility.UrlEncode(date) +
"&newtime=" + HttpUtility.UrlEncode(time) +
"&newname=" + HttpUtility.UrlEncode(name);
Is it secure?
No, not at all. Anyone could send a request to your target page with whatever values he feels good for him.
Is there a better way?
That would depend on your specific requirements and whether the information you are transmitting is sensitive or not. If it is sensitive information, then you might consider storing the values on the server instead of passing them as query string parameters. For example you could use the ASP.NET Session for this purpose.
Is it secure? No, of course not, the values are on the query string which gets sent to the browser. If you want to keep it secure put the values in session on the server side.
You are using QueryString Way to pass variables from one page to another page.its not a problem if the parameters are not secure like you cant pass secure info(Sensitive Information) like passwords,any important ids...
if you want to handle with secure parameters(Sensitive Information) you can use Sessions,Cookies..
In your case you are passing names.i hope it doesnt create any problems because this are not secure parameters(Sensitive info).even though if you feel any security risks you can use encryption and decryption concepts like encrypt your parameter name and pass it with url and then decrypt that parameter where you want to use.
Refer :
http://msdn.microsoft.com/en-us/library/6c3yckfw%28v=vs.100%29.aspx
http://www.codeproject.com/Articles/8055/Transferring-page-values-to-another-page
For better understanding about passing variables from one page to another page
Thank you guys for you help!
I have now changed it to Sessions. My code now looks like this:
In web page1:
string email = txtEmail.Text;
string date = txtDate.Text;
string time = txtTime.Text;
string name = txtName.Text;
Session["email"] = email;
Session["date"] = date;
Session["time"] = time;
Session["name"] = name;
Response.Redirect("~/change.aspx");
In web page2:
protected void Page_Load(object sender, EventArgs e)
{
string email = (string)(Session["email"]);
string date = (string)(Session["date"]);
string time = (string)(Session["time"]);
string name = (string)(Session["name"]);
TextBox1.Text = email;
TextBox2.Text = date;
TextBox3.Text = time;
TextBox4.Text = name;
}
Related
i have a big problem and i need your help. i'm trying send to url parameters to generate the pdf file with the library winnovative. when trying the first time I have no problems and generates pdf but if I want to get the pdf again this gives me error because the parameters in url they are sent and fail to request and falls when so finally assign to generate the pdf file.
I have attached the code for review:
public override void Pagina_PrimeraCarga(object sender, EventArgs e)
{
string datosRequest = Request.QueryString["DATOS"];
char delimitadores = ';';
string[] datos = datosRequest.Split(delimitadores);
imgBanco.Attributes.Add("ImageUrl", "~/App_Themes/Imagenes/Logo.gif");
System.DateTime fecha = new System.DateTime(2014, 12, 17);
lblDia.Text = Convert.ToString(fecha.Day);
lblMes.Text = Convert.ToString(fecha.Month);
lblAno.Text = Convert.ToString(fecha.Year);
string rutEmpresa = datos[3];
int rut = Convert.ToInt32(rutEmpresa);
string rutRes = rut.ToString("N0", CultureInfo.InvariantCulture).Replace(",", ".");
rutRes = rutRes + "-" + datos[4];
lblOficina.Text = "OFICINA: " + datos[0];
lblNombreTitular.Text = "NOMBRE TITULAR: " + datos[1];
lblRut.Text = "R.U.T.: " + rutRes;
lblDireccion.Text = "DIRECCION: " + datos[2];
lblFono.Text = "FONO: " + datos[5];
}
P.D: my apologies for my bad English but my native language is Spanish
P.D.2: Thanks to everyone who could help me in this case
I think that your problem is that after postBack your query string will be empty. Try this
add hiddenfield
<asp:HiddenField runat="server" ID="hidden1" />
then in your pageLoad
if (!IsPostBack)
{
string datosRequest = Request.QueryString["DATOS"];
if(datosRequest != null)
{
//do something
hidden1.Value = datosRequest ;
}
}
else
{
datosRequest = hidden1.Value;
}
I have solved the problem. I was thinking a bit and detects when passed a second time to obtain the pdf that was creating the cookie to be passed to the other form was created and therefore did not pass the data. for this reason I had to add 2 lines but my code for closing the pdf this server delete the cookie and when consulted again remove the client:
Response.Cookies.Clear ();
myCookie.Expires = DateTime.Now.AddDays (1D);
Ok. So this question might be a bit stupid but as I've searched and searched and haven't found a working solution I thought I might ask here.
I've put up a simple PHP page that gets 2 parameters from the url myusername and mypassword. Then gets 3 int values from a database according to the username and password given.
(tested it By typing the url in with the parameters and the PHP script itself works. Even made it to echo the 3 integers on the page to make sure)
Now to the problematic part. I'm using Visual Studio 2013 and making an Universal App for Windows 8.1. And I just can't seem to get the httpClient to get me any data from there. Through browsing the forums I haven't been able to find anything that works. Couldn't have tested all either as most use GetResponse() which doesn't work in VS 2013. As I'm fairly new to the C# coding it could be as simple as to a little mistake in the dozens of tests I've done.
Made a login screen with 2 text fields. And I can build the url in form of "www.something.com/something/somephp?myusername=UserNameGiven&mypassword=PasswordGiven"
If anyone could give a simple solution on how I might be able to get the results from the page that address opens (only shows the 3 integers through echo... can remove those too if those arent required for the C# code to work. String format would probably be ideal if not too much to ask...
Ok made a new GetScores async method for the code you gave SnyderCoder. Throwing that Task on login button would have required coding beyond my knowhow for the moment atleast.
Still Results.Text field remains at the default status and shows no change.
Changed the LoginButton back to async without task.
the state of my code from the c# is atm is
private async void LoginButton_Click(object sender, RoutedEventArgs e)
{
string UserName, Password;
UserName = UserNameFeedField.Text.ToString();
Password = PasswordFeedField.Text.ToString();
string url = "something.com/something/GetScores.php?myusername=" + UserName + "&mypassword=" + Password;
URL.Text = url;
// GetScores(url);
using (Windows.Web.Http.HttpClient client = new Windows.Web.Http.HttpClient())
{
string contentOFPage = await client.GetStringAsync(new Uri(url));
Results.Text = contentOFPage;
}
}
incase it matters here is the PHP code portion
<?php
$host="db_host"; // Host name
$username="db_user"; // Mysql username
$password="db_pswd"; // Mysql password
$db_name="db_name"; // Database name
$tbl_name="db_table"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// username and password sent from form
$myusername=$_GET["myusername"];
$mypassword=$_GET["mypassword"];
// To protect MySQL injection (more detail about MySQL injection )
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT field1 as LowB, field2 as LongB, field3 as Bs FROM $tbl_name WHERE UserID='$myusername' and UserPSWD='$mypassword'";
$result=mysql_query($sql);
// this part only shows the variables gotten from the query and echoes those on the page
// was only made to test that the PHP works.
while ($row = mysql_fetch_assoc($result)) {
echo ($row["LowB"] . " " . $row["LongB"] . " " . $row["Bs"]);
}
?>
First a async method always needs to return a task. For the rest:
private async void LoginButton_Click(object sender, RoutedEventArgs e)
{
string UserName = UserNameFeedField.Text.ToString();
string Password = PasswordFeedField.Text.ToString();
string url = "www.something.com/something/some.php?myusername=" + UserName + "&mypassword=" + Password;
using (Windows.Web.Http.HttpClient client = new Windows.Web.Http.HttpClient())
{
string contentOfPage = await client.GetStringAsync(new Uri(url));
//Do something with the contentOfPage
}
}
Hi there I am a beginner with developing on C#. I am having some problems passing data from one page to another. Within a listbox I have data which i have obtained from a database via web service.
I have created some coding to move sets of selected data to the next page and input it into the assigned text blocks. Currently this coding only works for one data field "eventId."
Could you please have a look at my code and tell me what I have done wrong and how i can fix this.
Here is my coding from the page which holds the listbox with the sets of data:
private void FirstListBox2_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
EventServiceReference1.Event myEvent = (EventServiceReference1.Event)FirstListBox2.SelectedItem;
int eventId = myEvent.EventID;
string eventList = myEvent.EventList;
string eventDescription = myEvent.Description;
string eventDate = myEvent.Date;
string eventTime = myEvent.Time;
string eventLocation = myEvent.Location;
var url = string.Format("/EventPageTemp.xaml?eventId={0}", eventId + "&eventList={0}", eventList);
NavigationService.Navigate(new Uri(url, UriKind.Relative));
}
Here is my coding from the "EventPageTemp" page which i am passing the data to:
int eventId;
string eventIdStr;
string eventList;
if (NavigationContext.QueryString.TryGetValue
("eventId", out eventIdStr) && int.TryParse(eventIdStr, out eventId))
{// load event data, and set data context
txtEID.Text = eventIdStr;}
if (NavigationContext.QueryString.ContainsKey("eventList"))
{
string val = NavigationContext.QueryString["eventList"];
txtEList.Text = eventList;
}
At the moment it is coming up with the errors:
- the name 'eventList' does not exist in current context
-use of unassigned local variable 'eventList'
Please can you help me figure this out. Thank you.
the issue is your url, eventId + "&eventList={0}", eventList will be pass as eventId:
var url = string.Format("/EventPageTemp.xaml?eventId={0}", eventId + "&eventList={0}", eventList);
it should be:
var url = string.Format("/EventPageTemp.xaml?eventId={0}&eventList={1}", eventId, eventList);
I'm trying to receive the values passed from other non aspx page to my asp.net page with C# via HTTP GET with Parameters. Would it be fine if I fetch the values with Request.QueryString in Page Load event?
Please advice.
Here's what I've done so far.
protected void Page_Load(object sender, EventArgs e)
{
//fetch query from url
string queryTimeStamp = Request.QueryString["t"];
Int64 queryCallerID = Convert.ToInt64(Request.QueryString["s"]);
int querySMSGateway = Convert.ToInt32(Request.QueryString["d"]);
string querySMSMessage = Request.QueryString["m"];
//Do other processings
}
you can get the value in Request.QueryString or Request.Form collection
Below is the better way to go, which will handle unexpected exception, thanks:
string queryTimeStamp = Request.QueryString["t"];
Int64 queryCallerID;
Int64.TryParse(Request.QueryString["s"] == string.Empty ? "0" : Request.QueryString["s"], out queryCallerID);
int querySMSGateway;
Int32.TryParse(Request.QueryString["d"] == string.Empty ? "0" : Request.QueryString["d"], out querySMSGateway);
string querySMSMessage = Request.QueryString["m"];
I am using C#. Below is my sample code.
private void Page_Load(object sender, System.EventArgs e)
{
string str = Request.UrlReferrer.ToString();
Label1.Text = str;
}
The result in Label1.Text is http://localhost:82/data/WebForm1.aspx.
Now I want the result "WebForm1.aspx" in Label1.Text
can you please help me?
Thanks.
If you want only the part after the last / in the URL, calling the System.IO.Path.GetFileName() method on the Uri.LocalPath should do the trick:
System.IO.Path.GetFileName(Request.UrlReferrer.LocalPath);
If you want the output to keep query string information from the URI, use the PathAndQuery property:
System.IO.Path.GetFileName(Request.UrlReferrer.PathAndQuery);
Try the LocalPath property on the UrlReferrer:
Label1.Text = Request.UrlReferrer.LocalPath;
It should provide you with just the filename.
Edit: this seems to also include the path, so only works for root.
In which case, you're better off just using Substring():
string str = Request.UrlReferrer.ToString();
Label1.Text = str.Substring(str.LastIndexOf('/')+1);