Send data from one page to another - c#

I am trying to send form data from one page to another using C# ASP.Net. I have two pages default.aspx and default2.aspx.Here is the code I have in default.aspx:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" Text="Go"
PostBackUrl="~/Default2.aspx" />
<br />
From what I know so far the PostBackUrl is used to set the page in which you want the data to be sent is this correct?
Also how can I retrieve the data that is sent to Default2.aspx?

You have a few options, consider
Session state
Query string
Session state
If you are going to send data between pages, you could consider the use of Session State.
ASP.NET session state enables you to store and retrieve values for a
user as the user navigates ASP.NET pages in a Web application. HTTP is
a stateless protocol. This means that a Web server treats each HTTP
request for a page as an independent request. The server retains no
knowledge of variable values that were used during previous requests.
ASP.NET session state identifies requests from the same browser during
a limited time window as a session, and provides a way to persist
variable values for the duration of that session. By default, ASP.NET
session state is enabled for all ASP.NET applications.
Best of all, it is easy!
Put data in (for example on default1.aspx)
Session["FirstName"] = FirstNameTextBox.Text;
Session["LastName"] = LastNameTextBox.Text;
Get it out (for example on default2.aspx)
string firstname = Session["FirstName"] // value of FirstNameTextBox.Text;
string lastname = Session["LastName"] // value of LastNameTextBox.Text;
Query string
If you are sending small amounts of data (eg id=4), it may be more practical to use query string variables.
You should explore the use of the query string variables, e.g.
http://www.domain.com?param1=data1&param2=data2
You can then get the data out like
string param1 = Request.QueryString["param1"]; // value will be data1
string param2 = Request.QueryString["param2"]; // value will be data2
You can use something like How do you test your Request.QueryString[] variables? to get the data out.
If you are unfamiliar with querystring variables check out their wikipedia article

Session variables can be useful in this context.
Foe example suppose your textboxes contain login credentials, then save them in sessions so that you can later use them in any other page. Like this:
In Button_Click-
Session["name"]=TextBox1.Text;
Session["pwd"]= TextBox2.Text;
Instead of PostBackUrl="~/Default2.aspx" you can write the following-
//in button click
Server.Transfer("~/Default2.aspx");
In Default2.aspx page load:
string a= Session["name"].ToString();
string b= Session["pwd"].ToString();

Try this in the Page_Load of Default2.aspx.
if (PreviousPage != null)
{
if (((TextBox)PreviousPage.FindControl("TextBox1")) != null)
{
string txtBox1 = ((TextBox)PreviousPage.FindControl("TextBox1")).Text;
Response.Write(txtBox1);
}
}
And yes you are correct, the data from page 1 will be sent to page 2 if you use the PostBackUrl attribute.
MSDN link

While all the answers here will work some aren't the most efficient. Why would a simple/standard http POST have to invoke (expensive) server-side Sessions?
Your code isn't doing anything special - it is simply POSTing a form to another page. All you need to do to obtain the POSTed data is go through the Request.Form collection.
Prior to the availability to set the PostBackUrl (if memory serves version 1 of asp.net), Server.Transfer and getting references to the previous page was how cross-page POSTing was done/documented. However, with PostBackUrl, things go back to basics, the way it should be - a standard http POST from one resource to another.
Here's a similar SO thread that maybe helpful.

another way is to save the data on a database and fetch it back on the other page:
//update
string query = "UPDATE table SET col = 'a'";
SqlCommand command = new SqlCommand(query, connection);
command.ExecuteScalar();
//select
string query = "SELECT col FROM table";
SqlCommand command = new SqlCommand(query, connection);
string value = command.ExecuteScalar();

Related

Is It possible to serialize the session object in ASP Classic? [duplicate]

We have a website in classic asp that we are slowly migrating to ASP.NET as necessary.
The problem of course is how classic asp and ASP.NET handle Sessions. After spending the last few hours researching the web, I found many articles, but not one that stood out over the others.
Is there a best practice for transferring session variables from and to classic asp and asp.net? Security is a must and any explanation with examples is much appreciated.
A simple bridge to pass a single session variable from classic asp to .net serverside (hiding your sessionvalue from the client), would be this:
On the ASP end: An asp page to output your session, call it e.g. asp2netbridge.asp
<%
'Make sure it can be only called from local server '
if (request.servervariables("LOCAL_ADDR") = request.servervariables("REMOTE_ADDR")) then
if (Request.QueryString("sessVar") <> "") then
response.write Session(Request.QueryString("sessVar"))
end if
end if
%>
On the .net end, a remote call to that asp page. :
private static string GetAspSession(string sessionValue)
{
HttpWebRequest _myRequest = (HttpWebRequest)WebRequest.Create(new Uri("http://yourdomain.com/asp2netbridge.asp?sessVar=" + sessionValue));
_myRequest.ContentType = "text/html";
_myRequest.Credentials = CredentialCache.DefaultCredentials;
if (_myRequest.CookieContainer == null)
_myRequest.CookieContainer = new CookieContainer();
foreach (string cookieKey in HttpContext.Current.Request.Cookies.Keys)
{
' it is absolutely necessary to pass the ASPSESSIONID cookie or you will start a new session ! '
if (cookieKey.StartsWith("ASPSESSIONID")) {
HttpCookie cookie = HttpContext.Current.Request.Cookies[cookieKey.ToString()];
_myRequest.CookieContainer.Add(new Cookie(cookie.Name, cookie.Value, cookie.Path, string.IsNullOrEmpty(cookie.Domain)
? HttpContext.Current.Request.Url.Host
: cookie.Domain));
}
}
try
{
HttpWebResponse _myWebResponse = (HttpWebResponse)_myRequest.GetResponse();
StreamReader sr = new StreamReader(_myWebResponse.GetResponseStream());
return sr.ReadToEnd();
}
catch (WebException we)
{
return we.Message;
}
}
I've used an ajax bridge (for want of a better term), specifically, a classic asp page that reads all session vars into a database with a guid, it then redirects to a .net page passing the guid in the querystring, the asp.net page reads from sql for the given guid and created those vars as sessions.
Eg, in classic asp (pseudocode code - just to give you an idea, use parameterised queries in yours etc):
'#### Create GUID
Dim GUID 'as string
GUID = CreateWindowsGUID() '#### Lots of methods on http://support.microsoft.com/kb/320375
'#### Save session to sql
For Each SessionVar In Session.Contents
db.execute("INSERT INTO SessionBridge (GUID, Key, Value) VALUES ('" & GUID & "', '" & SessionVar & "', '" & session(SessionVar) & "')")
Next
Then, in a .net page:
'#### Fetch GUID
Dim GUID as string = Request.QueryString("GUID")
session.clear
'#### Fetch from SQL
db.execute(RS, "SELECT * FROM SessionBridge WHERE GUID = '" & GUID & "'")
For Each db_row as datarow in RS.rows
Session(db_row("Key")) = db_row("Value")
Next
As i say, this is very rough pseudocode, but you can call the asp with a simple background ajax function, then call the .net page for the given GUID.
This has the advantage of not exposing all your vars and values to the client (as post methods do etc).
They use different sessions, so you'll need to devise some way of transferring the vars yourself. You could include them in cookies, or send them via HTTP POST (i.e. a form with hidden fields) to the asp.net side.
Alternatively, you could scrap using session storage and stick everything in a database for each user/session, then just pass a session key from classic ASP to ASP.NET via one of the above suggestions. I know this sounds like you're reinventing the wheel, but this might be one of those cases where you just can't get around it.
I have a website that does that exact action. The secret is to use an intermediate page with the asp function response.redirect
<%
client_id = session("client_id")
response.redirect "aspx_page.aspx?client_id=" & client_id
%>
This is an example to pull the classic asp session variable client_id and pass it to an aspx page. Your aspx page will need to process it from there.
This needs to be at the top of a classic asp page, with no HTML of any type above. IIS will process this on the server and redirect to the aspx page with the attached query string, without sending the data to the client machine. It's very fast.
In case anyone else stumbles here looking for some help, another possible option is to use cookies. The benefit of a cookie is that you can store reasonable amounts of data and then persist that data to your .Net application (or another web application). There are security risks with exposing a cookie since that data can be easily manipulated or faked. I would not send sensitive data in a cookie. Here the cookie is only storing a unique identifier that can be used to retrieve data from a table.
The approach:
Grab the session data you need from your classic asp page. Store
this data in a table along with a unique hash and a timestamp.
Store the value of the hash in a short-lived cookie.
Redirect to whatever page you need to go and read the hash in the cookie.
Check that the hash in the cookie hasn't expired in the database. If it is valid, send back the data you need to your page and then expire the hash so it can't be reused.
I used a SHA 256 hash that was a combination of the user's unique identifier, session ID, and current timestamp. The hash is valid for only a few minutes and is expired upon reading. The idea is to limit the window for an attacker who would need to guess a valid hash before it expired.

How to send data to another page except query string in Web-Farm

I have a webFarm application and an HTML image control as follows
<img id="logo" runat="server" src="" width="200" height="300" />
I am setting scr of this image from code behind as follows-
string mapId = "1234"; // mapId can vary
logo.Src = "./logo.aspx?mapId=" + mapId ;
Here logo.aspx is simple aspx page with following Page_load code-
logo.aspx
protected void Page_Load(object sender, EventArgs e)
{
Response.Clear();
Response.ContentType = "image/jpeg";
int mapIdValue= int.Parse(Request.Params["mapId"]); // mapId from querystring
string data = someFunction(mapIdValue); // to get image in Base64 String format
Response.BinaryWrite(Convert.FromBase64String(data));
Response.End();
}
This works fine.
My problem is, I dont want to send mapId in query string as it is exposed to user. So what would be the possible ways to send mapId from my page to logo.aspx.
I cant use session or HttpContext Items Collection as it is a Webfarm.
I tried using previousPage but not working for me..
Any ideas on this?
As the browser will retrieve the image in a subsequent, independent request, the server needs to be able to recognize the map id in this new request. It is not generally impossible to use sessions in a web farm, but it requires some kind of state server/database that all the servers in the farm share.
If you are unable to use sessions in your web farm, you need to transmit some information to the client that is used in the new request to identity the map. Independent of the way you choose, the client gets hold of some id information. Even though you do not want to use a query parameter, I'd still prefer using query parameters as opposed for instance using a cookie to hand over the id to the client. The main reason is that it will also work if you have several maps on a page.
In order to hide the real id for the client you can create an artificial id, e.g. a GUID that you can use to retrieve the image. You'd need to store the artificial id so that you can identify the map.
You can limit the artificial id so that it is valid only for some time, a number of requests or for a specific user. This way, the client is only able to use the artificial id in a very limited amount of time.
Of course, this requires some effort, but should be a stable way also in a Webfarm.
it may be usefull. please refer the below link
http://www.c-sharpcorner.com/UploadFile/gopenath/Page107182007032219AM/Page1.aspx

Is sending Session from javascript safe?

Well, this is a bit weird i think to ask this question, because i am not sure if that's the place to ask that.
OK, into the question..
I have this code
<script>
var session = "<%= Session["User"]%>";
</script>
So, i was thinking, is that safe? let me tell you what i mean..
I have a web api which you can get the name, last name, age and everything about the user with his Session, can i send this web api this session and use it?
Is that a safe thing to do ? in matter of securiy? if not, is there any better way?
EDIT 1:
What am i trying to aaccomplish? simple, i will store the UserId in the session, the UserId will Guid, when the user is loogin in the javascript can send post to an API server to get info, the API will send the UserId from the session.
Is That ok?
Workflow that you describe looks fine. For me it seems safe to use some ID to get more information about some user, especially if this is supposed to be an API, at least, Facebook API uses such principle not being afraid of some hackers :)
My main concern here is the coding style when you try to mix code and view which is not good. If you really need to share some information between client and server sides then I would go with one of these options.
Option # 1 - Cookies
What is the difference between a Session and a Cookie?
You can keep some simple information in a cookie and get it this way :
Client : $.cookie('ID')
Server : Response.Cookies["ID"]
In this case there is no need to put in a mess your client side JS with C# code and cookies will be saved on users PC which means that nobody will see them except him.
Option # 2 - Templates
Server : put all needed information into hidden form or ViewState
Client : take information from hidden form using HTML selectors
Straight answer :
In general, if you worry only about safety then it is fine to use this code, it should not break security of your site.
Although, personally I do not like this approach because :
you will mix code and view, MVC was created to split them
it is not clear where exactly in your view you will put this code and thus it is not clear how you are going to check that this variable was initialized
it may happen that you will put there some value that will break JS syntax and will cause JS error
In my personal opinion, I would replace it with one of the mentioned options.
Option 1 - MVC + JQuery + Cookie Example
public ActionResult Index()
{
string demo = Request.QueryString["MyNameSpace.ID"]; // get value from client
Response.Cookies["MyNameSpace.ID"].Value = "server"; // change value in response
return View();
}
Then in your JS file :
$(document).ready(function() { // make sure server rendered page
var ID = $.cookie('MyNameSpace.ID'); // get cookie value from server
$.cookie('MyNameSpace.ID', 'client'); // update, on the next request server will get it
});
Option 2 - MVC + JQuery + Templates Example
public class OptionsModel // View Model
{
public string ID { get; set; }
public string User { get; set; }
}
public ActionResult Index() // Controller
{
OptionsModel options = new OptionsModel();
options.ID = "server";
return View(options);
}
Your view :
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<OptionsModel>" %>
<%=Html.HiddenFor(m => Model.ID, new { #class = "MyNameSpace:ID" })%>
<%=Html.HiddenFor(m => Model.User, new { #class = "MyNameSpace:User" })%>
Then in your JS file :
$(document).ready(function() { // make sure server rendered page
var options = $('[class^=MyNameSpace]') // get values from hidden fields
options[0] = 'client'; // update data
$.ajax({ data : options }); // create handler to send data back to server
});
Examples for Web Forms do not differ significantly.
The code you have posted will be rendered on the page as so when it hits the client (assuming you are using ASP.NET
<script>
var session = "John Smith";
</script>
This is due to the use of the server side scripting tags <%= %> (https://technet.microsoft.com/en-us/library/cc961121.aspx)
As a note its probably not the best thing in the world to fully expose the session to javascript if that is your intention. At the end of the day it depends what you are storing in there and using it for (but ASP.NET will also use it for certain things) but exposing it just opens another area for someone to attack.
http://www.owasp.org is a great place to learn more about securing your website.

How to count Number of refreshes of web page

I have a web form of Asp.Net, in which I want JavaScript to count how many time i have refreshed the page.
If you want to do it on clientside just save (and retrieve) the information on localstorage every time load event occurs
Do you want to count this per user ? Or for whole application ?
If you are doing for whole application you can use application variable in Global.asax on each page request . But that might get lost if your application recycles .
If you want to do for each user You can use server side sessions or cookies on clientside .
You can set the value in a cookie using js or asp, or in a session value (for a single user) or in application value (for all the users), is not necessary javascript.
You have to put this code server side on page load.
For all users:
Application["refresh_count"] =
Convert.ToInt64(HttpContext.Current.Application["refresh_count"]) + 1;
For a single user with session:
Session["refresh_count"] = Convert.ToInt64(Session["refresh_count"]) + 1;
OR
Response.Cookies["UserSettings"]["refresh_count"] = Convert.ToInt64(Response.Cookies["UserSettings"]["refresh_count"]) + 1;
Response.Cookies["UserSettings"].Expires = DateTime.Now.AddDays(1d);
You can save this in the Session Object.
You can use jQuery calling prepared address.
For example:
$.ajax({
url: ".../countPageRefreshes.aspx",
data: { page: "thisPageAddress" }
})
Then, in countPageRefreshes you can increase number of times, page was refreshed and save it somewhere.

Load data from database in _layout.cshtml

I am creating a web application using ASP.NET MVC 4.
I want to display the user's nickname on all of pages, so I have to load it in _layout.cshtml.
Please note that I'm storing user's nickname manually. (In my own database and my own tables.)
I can add user's User name by Membership.GetUser().UserName, but I want to load his nickname from database and show it in _layout.cshtml.
How to do that?
Let me give a simple solution for what you want:
write an action in a controller (mine is CommonController):
public ActionResult NickName()
{
SqlConnection cn = new SqlConnection(cnstr);
SqlCommand cmd = new SqlCommand(cmdStr, cn);
cn.Open();
SqlDataReader dr = cmd.ExecuteReader();
string nickName = string.Empty;
while (dr.Read())
{
nickName = dr["nick_Name"].ToString();
}
dr.close()
return Content(nickName);
}
put the below line in everywhere you want in _Layout:
nickname = #{Html.RenderAction("NickName", "Common");}
Finished!
Thanks to #SergRogovtsev for recommending:
nickname = #Html.Action("NickName", "Common")
first asked:
Are you using entity framework?
You can use partial views in _Layout either using EF or ADO.
If you mean you can't access aspnet_membership table by using entity framework, you should ask your question in another way!
let me know more about your problem by giving some sample of your code.
I would advise you to upon logging in, store the username in a session variable (which is done by accessing the Session object, which implements a key=value pair architecture allowing you to store and retrieve your data at will). It's a drag on performance to have to make a database call for EVERY page that loads, and a single nickname string variable in session won't take up that much space on your server.
As far as loading the variable you could use the code posted by Vahid, but I would recommend you if your site is still in its infancy to take the extra time to learn and implement Entity Framework. It is cleaner, easier and Microsoft is really pushing data connection management in that direction.
I have used a combination of Mr_Creostoe and Vahid answers.
I am saving nickname in a session (as Mr_Cresotoe said), and if there isn't such session (for example, if user ticked remember me checkbox and is visiting after many time), I'll create that session using RenderAction. (As Vahid said).
Thank you guys!

Categories