Save data through session in C# web application - c#

I try to create a web application that got a button that change an image. this is my code:
public partial class _Default : System.Web.UI.Page
{
private bool test ;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
if (test)
{
Image1.ImageUrl = #"~/images/il_570xN.183385863.jpg";
test = false;
}else
{
Image1.ImageUrl = #"~/images/BAG.png";
test = true;
}
}
}
my problem is that the page reload every time. meaning, after i click the button "test" return to it's initial value. how can i have a variable that i can access all through the session?
please notice, i don't want to solve this specific image problem, but to know how to keep data until the user closed the page.

You can store arbitrary values in Session
Session["someKey1"] = "My Special Value";
Session["someKey2"] = 34;
Or more complex values:
Session["myObjKey"] = new MyAwesomeObject();
And to get them back out:
var myStr = Session["someKey1"] as String;
var myInt = Session["someKey2"] as Int32?;
var myObj = Session["myObjKey"] as MyAwesomeObject;

ASP.NET webforms are stateless so this is by design.
you can store your bool variable in the ViewState of the page so you will always have it updated and persisted within the same page.
Session would also work but I would put this local page related variable in the ViewState as it will be used only in this page ( I guess )

Store the variable in a cookie! :)
Example:
var yourCookie = new HttpCookie("test", true);
Response.Cookies.Add(yourCookie);

Session["show_image"] = "true";

To achieve what you want you need to check if is PostBack or not as so:
protected void Button1_Click(object sender, EventArgs e)
{
if (test && !IsPostBack)
{
Image1.ImageUrl = #"~/images/il_570xN.183385863.jpg";
test = false;
}else
{
Image1.ImageUrl = #"~/images/BAG.png";
test = true;
}
}
BUT, don't do it that way. You are approaching this wrong. You wouldn't want to store in Session things like whether this image is shown or not, etc. It's difficult to suggest an approach without knowing the specific issue you are facing.

Another option than the already mentioned would be to store the data in the ViewState. If it's just used in postback situations, that might be a possible way.
ViewState["test"] = true;
You save memory on the server but use a little bit of bandwith. The data gets lost, when the user browses to another page.

Related

Make a field read only based on value in ASP.net: C#, ASP.Net

Everyone that has responded to my questions have been so very helpful and I am closing in on finishing this app. My challenge now is to make 3 fields read only based on a login.
I have the following code that does exactly what I need and assign the currently logged in user to a text field. What I want to do is make some other text fields (Read Only) if the login user does not equal a specific value. For example, if submitted_by_email_username does not equal administrator1#samplecompany.com then make the text field (Salary_in) which is a textbox, Read Only. I can read code much than I write it these days so I apologize if this is a simple request. I would like to make three fields Read Only based on that logic in the COde Behind.
protected void Page_PreInit(object sender, EventArgs e)
{
if (submitted_by_email_username != null)
{
_ = Context.User.Identity.Name;
if (User.Identity.IsAuthenticated)
submitted_by_email_username.Text = User.Identity.Name;
}
}
First of all, you don't need code in Page_PreInit 99.9% of the time in webforms. Even with dynamic controls you would only need Page_Load.
But you can make a TextBox readonly by using the Enabled property.
protected void Page_Load(object sender, EventArgs e)
{
if (Request.IsAuthenticated)
{
submitted_by_email_username.Enabled = false;
submitted_by_email_username.Text = User.Identity.Name;
}
}

Resubmission on load asp.net c#

I am working on a C# project using asp framework 4.5 and I am having this problem :
I want a way to avoid a resubmission of the form on page refresh (without self redirect):
When refreshing the page, the button does trigger itself, I need to avoid the second submission without page redirection .
I am trying to upload a file, on the first try every thing is Working fine, but, when I hit f5 to refresh the page, the form will be resubmitted.
try below code
public bool IsPageRefresh = false;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["postids"] = System.Guid.NewGuid().ToString();
Session["postid"] = ViewState["postids"].ToString();
}
else
{
if (ViewState["postids"].ToString() != Session["postid"].ToString())
{
IsPageRefresh = true;
}
Session["postid"] = System.Guid.NewGuid().ToString();
ViewState["postids"] = Session["postid"].ToString();
}
}
just check below condition on button click
if (!IsPageRefresh)
{
// write you post code
}
try this it's working perfect for me .

Session variable + WebMethod variable value not updating

I have a web app with a dropdown list. When a new index is selected I have to storing the value to a session variable, which is created on Session_Start event.
protected void Session_Start(object sender, EventArgs e)
{
Session.Add("testValue", "test");
}
On selectedindex changed event i'm setting the new value like this
Session["testValue"] = DropDownList.SelectedItem.Text;
I have a web service where I retrieve the value of the session variable like this:
[WebMethod(EnableSession = true)]
public string getValue()
{
var testVal = Session["testValue"].ToString();
return testVal.ToString();
}
From a console app I connect to the web service and retrieve the value returned by getValue(), however the initial value is always being returned. any idea please?
The issue is because when the console app is run it seems that a new session is created. Using Application state using Application.Set and Application.Get solved the issue. Hopefully i will not have issues when the system will be used by multiple users.
Check whether the values of the items in your dropdown list are different.This is essential for your selected index changed event to be fired.
Here the values are not changed, You didn't change the values. So nothing expected
public string getValue()
{
var testVal = Session["testValue"].ToString();
return testVal.ToString();
}
The mistake is probably in dropdownlist
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Session["testValue] = dropdownlist1.SelectedItem.text;
}
}
And,
protected void dropdownlist1_SelectedIndexChanged(object sender, EventArgs e)
{
Session["testvalue"] = dropdownlist1.SelectedItem.text;
}
Also try with
System.Web.HttpContext.Current.Session["testvalue"]
in both parts

session,cookies in asp.net c#

i want to pass a string value from one page to another.Also i have some text boxes and the values entered in it needs to be passed to a new page.How do i do it?
I have a string S
String S = Editor1.Content.ToString();
i want to pass value in string S onto a new page i.e Default2.aspx how can i do this in ASP.net C#
You can achieve it using Session or by QueryString
By Session
In your first page:
String S = Editor1.Content.ToString();
Session["Editor"] = S;
Then in your next page access the session using:
protected void Page_Load(object sender, EventArgs e)
{
String editor = String.Empty;
if(!String.IsNullOrEmpty(Session["Editor"].ToString()))
{
editor = Session["Editor"].ToString();
// do Something();
}
else
{
// do Something();
}
}
-
By QueryString
In your first page:
// or other events
private void button1_Click(object sender, EventArgs e)
{
String S = Editor1.Content.ToString();
Response.Redirect("SecondPage.aspx?editor" + S)
}
In your second page:
protected void Page_Load(object sender, EventArgs e)
{
string editor = Request.QueryString["editor"].ToString();
// do Something();
}
Depends on what the value is. If it is just a parameter and is ok to be viewed by the user then it can be passed through QueryString.
e.g.
Response.Redirect("Default2.aspx?s=value")
And then accessed from the Default2 page like
string s = Request.QueryString["s"];
If it needs to be more secure then consider using session, but I wouldn't recommend using the Session excessively as it can have issues, especially if you are storing the session InProc which is ASP.NET default.
You can have a state server or database but, it might be better to have your own database based session based on the authenticated user, and have it cached in the website if need be.
Use Session["content"]=Editor1.Content.ToString() in page1...
in page2 use...string s = Session["content"]

Storing session variables in ASP.NET page?

How can I put variables that have scope the whole session on ASP.NET Page (I mean in the class that stands behind the aspx page)? Is the only way to put the variable in the Session object?
For example:
public partial class Test_ : System.Web.UI.Page
{
private int idx = 0;
protected void Button1_Click(object sender, EventArgs e)
{
Button1.Text = (idx++).ToString();
}
}
I want on every click on this button my index to go up. How can I do this without using the Session object?
You can put it in ViewState instead
public partial class Test_ : System.Web.UI.Page {
protected void Button1_Click(object sender, EventArgs e) {
if(ViewState["idx"] == null) {
ViewState["idx"] = 0;
}
int idx = Convert.ToInt32(ViewState["idx"]);
Button1.Text = (idx++).ToString();
ViewState["idx"] = idx;
}
}
ViewState seems to be what you're looking for here, so long as that counter doesn't need to be maintained outside the scope of this page. Keep in mind that a page refresh will reset the counter though. Also, if the counter is sensitive information, be wary that it will be stored (encrypted) in the rendered HTML whereas Session values are stored server-side.
There are a number of options besides the session. Take a look at Nine Options for Managing Persistent User State in Your ASP.NET Application.
For this sort of data, you probably would want use the session store.

Categories