The way I set my code won't let me obtain information from the previous page.
information on page 1:
public string Name{ get { return FirstName.Text; } private set{} }
public string Email { get { return email.Text; } private set { } }
information on page two (to obtain):
Mark up code:
<%# PreviousPageType VirtualPath="~/Registration.aspx" %>
c# code:
protected void Page_Load(object sender, EventArgs e)
{
string name = "";
string email = "";
if (PreviousPage != null)
{
name = PreviousPage.Name;
email = PreviousPage.Email;// both fields are always null... why?
}
I changed my last section to this: still wont work
Response.Redirect("CheckYourEmail.aspx");
}
ViewState["LoginName"] = FirstName.Text;
ViewState["Email"] = email.Text;
ViewState["Password"] = password1.Text;
}
public string Name { get { return ViewState["LoginName"].ToString() ; } private set { } }
public string Email { get { return ViewState["Email"].ToString(); } private set { } }
public string UserPassword { get { return ViewState["Password"].ToString(); } private set { } }
i also tried with Request["Email"];
wont work
Save the values in the session object and get these values from the other page.
// When retrieving an object from session state, cast it to
// the appropriate type.
ArrayList customers = (ArrayList)Session["Customers"];
// Saving into Session to be retrieved later.
Session["Customers"] = customers;
As far as I can see your code looks correct. Do you have viewstate enabled for the textboxes?
When you do a cross page postback the lifecycle of the source page starts over again. As soon as the target page accesses the PreviousPage Property.
Can you get the values through the Request object?
Request["FirsName"]
Http protocol is an state Less Protocol.
Try to use Session or cache to persist data.
The previous page's instance is simply gone, so there's no way to retrieve data from it...
Related
I want to pass an id back and forth in every page. I can not use session, application variables and database since I want it is base on page. Hidden field if a form exists or url concatenation are what I can think about.
Is there an easy way to get and send this id without manually adding it to url or hidden field in every page? For example, use a master page or a url rewriting method.
setup a public string value in your master page
Public partial class MasterPage:System.Web.UI.MasterPage
{
public string myValue
{
get{return "Master page string value" ;}
set {}
}
}
Access the property in your child page
protected void Page_Load(object sender, EventArgs e)
{
MasterPage mp = (MasterPage) Page.Master;
myLabel.text = mp.MyValue
}
An idea:
Place a hidden field in the master page:
<asp:HiddenField runat="server" ID="hdCrossPageValue"/>
Use this extension method to get/set that value from every page:
public static class Util
{
public static string GetCrossPageValue(this Page page)
{
if (page == null || page.Master == null) return null;
var hf = page.Master.FindControl("hdCrossPageValue") as HiddenField;
return hf == null ? null : hf.Value;
}
public static void SetCrossPageValue(this Page page, string value)
{
if (page == null || page.Master == null) return;
var hf = page.Master.FindControl("hdCrossPageValue") as HiddenField;
if (hf != null)
{
hf.Value = value;
}
}
}
Like this:
this.SetCrossPageValue("my cross page value");
var crossPageValue = this.GetCrossPageValue();
You can transfer it with the request url as parameter.
example
In page 1 you redirect to page 2 with parameter Test
Response.Redirect("Page2.aspx?param1=Test");
In page 2 you get it like:
if (Request.QueryString["param1"] != null)
var param1 = Request.QueryString["param1"];
I am trying to create a program that mimics an ATM. In my program, I need to check if the string that a user enters matches the Name property of any objects within a list of objects. If it does not match, then the account is automatically added with some other default values. If it does match, then I need to set the variables that are accessed on another form to the properties of that account object. Additionally, those properties will need to be updated from the other form, so that the object is kept current. I think that I can figure out how to update those properties, but I am having difficulty with trying to set the variables to the current account, more specifically, how to access the properties of the matching account. My class constructor is as follows:
class Account
{
private string name;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
private int acctNum = 0;
public int AcctNumber
{
get
{
return acctNum;
}
set
{
acctNum = value;
}
}
//initialize the CheckBalance value to 100.00
private decimal checkBalance = 100.00M;
public decimal CheckBalance
{
get
{
return checkBalance;
}
set
{
checkBalance = value;
}
}
public Account(string Name)
{
this.Name = Name;
}
private decimal saveBalance = 100.00M;
public decimal SaveBalance
{
get
{
return saveBalance;
}
set
{
saveBalance = value;
}
}
}
This works out just fine, as the only constructor that I need is the Name property, while the other properties are automatically set to a base value. The list and relevant code that I currently have are as follows:
//variable that will be used to check textbox1.Text
string stringToCheck;
//array of class Account
List<Account> accounts= new List<Account>();
public MainMenu()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//set value to user's input
stringToCheck = textBox1.Text;
//set a var that only returns a value if the .Name already exists
var matches = accounts.Where(p => p.Name == stringToCheck);
//check through each element of the array
if (!accounts.Any())
{
accounts.Add(new Account(stringToCheck));
}
else if (matches != null)
//set variables in another form. not sure if these are working
Variables1.selectedAccount = ;
//is this calling the CheckBalance of the instance?
Variables1.selectedCheckBalance = accounts[i].CheckBalance;
//same thing?
Variables1.selectedSaveBalance = accounts[i].SaveBalance;
//switch to form
AccountMenu acctMenu = new AccountMenu();
this.Hide();
acctMenu.Show();
}
In the above code, the "else if (matches != null)" is more of a filler, since I am not sure what to use. Of course, I also need to re-write the portion "if (!accounts.Any())" because once the list is populated with at least one object, this code will never occur again. So, really, I just need to know how to check for a matching account and how to access the properties of that account so that I can set the Variables1 properties to match. Thanks for any help!
If it works for your particular situation, var account = accounts.FirstOrDefault(p => p.Name == stringToCheck) will give you the first account in the collection that matches the expression or null if nothing exists.
check if account != null to ensure you do not get a null reference exception when trying to get property values.
Then, use account.CheckBalance to get the property value for that particular account.
I may not be fully understanding the question and cannot comment because I do not have a 50 reputation : (
I have a class named "admin" in my asp.net C# project.
It is:
public class Admin
{
private int ID;
private string FirstName, LastName, IsMainAdmin, Email, Username,
Password,BirthDate, EntryDate;
public int id
{
get { return ID; }
set { ID = value; }
}
public string firstname
{
get { return FirstName; }
set { FirstName = value; }
}
public string lastname
{
get { return LastName; }
set { LastName = value; }
}
.
.
.
After login a session is created like this:
Admin admin = isAdmin(username, password);
if (admin != null)
{
**Session.Add("maskanAdmin", admin);**
Response.Redirect("panel.aspx");
}
In other page i need to get admin's ID from session in code behind section after page request via jquery ajax.
Please notice that my code behind Method is [WebMethod] that is not supporting Session Object.
Can i get it? How?
var adminObj = (Admin)Session["maskanAdmin"];
if(adminObj != null)
{
var id = adminObj.id;
var fname = adminObj.firstname;
}
Read more about Read Values from Session State
Update
I am not sure why the question is updated after one hour saying you are using the code in web methods.
However, have a look at Using ASP.NET Session State in a Web Service
You just need to cast it back to an Admin type object when you retrieve it from the Session:
Admin admin = (Admin)Session["maskanAdmin"];
Then you can use the properties of the object as normal:
if(admin.ID == someOtherID)
{
// do stuff
}
Admin variableName = (Admin)Session["maskanAdmin"];
var adminObj = Session["maskanAdmin"];
if(adminObj != null)
{
var admin = (Admin)adminObj;
}
i want to store the login information {id,bagian} so i created Session.cs class.
here is the Session.cs code
class Session
{
public Session ()
{
}
public int idnya { get; set; }
public string bagiannya { get; set; }
public void saveSession(int id, string bagian)
{
idnya = id;
bagiannya = bagian;
}
public void destroySession()
{
idnya = 0;
bagiannya = "";
}
}
so the id will be generated automatically in the following form. however, why does the id return 0 ?
here is my Tambah constructor
public Tambah()
{
InitializeComponent();
textBox2.Text = session.idnya.ToString();
}
here is my Login code. iam using saveSession() method to store the id and bagian into Session.cs class
int nomornya = int.Parse(textBox1.Text);
string passwordnya = textBox2.Text;
string bagiannya = comboBox1.Text;
var data = from a in de.karyawan
where a.nomor_karyawan == nomornya &&
a.password == passwordnya &&
a.bagian == bagiannya
select a;
if (data.Any())
{
if (bagiannya.Equals("Admin"))
{
cmd.cetakSukses("Login sebagai admin", "Login");
loginAdmin();
}
else
{
cmd.cetakSukses("Login sebagai teller", "Login");
loginTeller();
}
main.Show();
this.Hide();
session.saveSession(nomornya, bagiannya);
//MessageBox.Show(session.idnya.ToString());
}
else
{
cmd.cetakGagal("Username atau password salah", "Login");
}
when i call the idnya and bagiannya value, they show the expected values. but, it went wrong when i call the Tambah form.
how to resolve this ?
or is there any alternative way without generating Session class manually ?
any help will be apprciated. thanks !
From the picture and the fact that you suggest that the code doesn't crash I guess that "textBox1" is the second TextBox control in the picture. This control contains text "0", so after you parse this text into an integer it will give you 0. After that, you don't modify this variable ("nomornya" whatever this means), so how do you expect it no to be 0? Besides all this, your question is cluttered and unclear.
EDIT: it is still unclear what do you expect to happen and why. What's the scenario? If the ID comes from the user, how is anyone suppose to guess what are you typing into the textBox1 what produces the unwanted results? When does the "id return 0" as you've stated?
I have a static class in my solution that is basically use a helper/ultility class.
In it I have the following static method:
// Set the user
public static void SetUser(string FirstName, string LastName)
{
User NewUser = new User { Name = String.Format("{0}{1}", FirstName, LastName) };
HttpCookie UserName = new HttpCookie("PressureName") { Value = NewUser.Name, Expires = DateTime.Now.AddMinutes(60) };
}
User is a simple class that contains:
String _name = string.Empty;
public String Name
{
get { return _name; }
set { _name = value; }
}
Everything works up until the point where I try to write the cookie "PressureName" and insert the value in it from NewUser.Name. From stepping through the code it appears that the cookie is never being written.
Am I making an obvious mistake? I'm still very amateur at c# and any help would be greatly appreciated.
Creating the cookie object is not enough to have it sent to the browser. You have to add it to the Response object also.
As you are in a static method, you don't have direct access to the page context and it's Response property. Use the Current property to access the Context of the current page from the static method:
HttpContext.Current.Response.Cookies.Add(UserName);