Say there is a TextBox on an ASP.NET page
<asp:TextBox id="DateTextBox" runat="server" />
with some value set in the code-behind.
How to access that value from another class of C# code-file through HttpContext or any other way?
You can access a property in you page via HttpContext even from a static method.
in your page:
public string DateTextBoxText
{
get{ return this.DateTextBox.Text; }
set{ this.DateTextBox.Text = value; }
}
somewhere else(even in a different dll):
public class Data
{
public static string GetData()
{
TypeOfYourPage page = HttpContext.Current.Handler as TypeOfYourPage;
if (page != null)
{
return page.DateTextBoxText;
//btw, what a strange method!
}
return null;
}
}
Note that this works only if it's called from within a lifecycle of this page.
It's normally better to use ViewState or Session to maintain variables across postback. Or just use the property above directly when you have a reference to this page.
You can create a public property within the control that returns a reference to the textbox.
You can then use this property to reference the textbox.
OR
You can store in into session and then access it in your entire application.
Store it in the HttpContext Session http://www.codeproject.com/Articles/32545/Exploring-Session-in-ASP-Net
//Storing UserName in Session
Session["DateTextBox"] = DateTextBox.Text;
Now, let's see how we can retrieve values from session:
//Check weather session variable null or not
if (Session["DateTextBox"] != null)
{
// use it...
}
You could place the value in the Session during the post back. Then access it from the Session in the other class. So in your form load event write this:
Session["MyValue"] = DateTextBox.Text
and then in the other class write this:
var val = HttpContext.Current.Session["MyValue"];
Related
I am trying to pass a few parameters between two web pages
within the source page I have the following properties
private string _testString { get; set; }
public string TestString
{
get
{
return _testString;
}
}
In previous msdn examples the return type was always set to a UI element (textbox.text)
However I am trying to pass the value from a dynamically generated link button which is why I chose to use the private accessor
In the click event of the link button on the source page I have the following:
protected void RenderReportInNewPage(LinkButton lb)
{
_testString = lb.CommandArgument.ToString();
Response.BufferOutput = true;
Response.Redirect("~/stuff/testviewer.aspx");
}
On the target page I have the source page referenced in the aspx as follows:
<%# PreviousPageType VirtualPath="~/stuff/testviewer.aspx"%>
And then in the codebehind of the target page I have the following:
Textbox.Text = PreviousPage.TestString;
PreviousPage displays the public property TestString but it is always null (as I don't think it is getting set but not sure why)
Is is possible to set a private accessor (_teststring) and have that value reflected within the public property? I'd appreciate any suggestions on what I have done wrong.
-Cheers
Found the error. It was not in the setting of the property but in how I was invoking the target page. In order to pass the properties across I needed to user Server.Transfer instead of Response.Redirect
protected void RenderReportInNewPage(LinkButton lb)
{
_testString = lb.CommandArgument.ToString();
Response.BufferOutput = true;
Server.Transfer("~/ReportBuilder/viewer.aspx");
}
-cheers
NET Experts,
I got an ASP.NET MVP (Model View Presenter) application, where I am using GenMaster.Master (Master Page), Metadata.aspx (Start Page), Global.asax etc.
I am accessing the Session["EncryptedQuery"] in both GenMaster.Master (Master Page) and Metadata.aspx (Start Page).
Our Session declaration convention is to use property as follows:
public string EncryptedQuery
{
get
{
object SessionObject = Session["EncryptedQuery"];
return (SessionObject == null) ? String.Empty : (string)SessionObject;
}
set
{
Session["EncryptedQuery"] = value;
}
}
Now, where should I declare this Session property to access it in Master as well as all the content pages? And I do not want to assign/retrive to/from Session["EncryptedQuery"] direcly.
Thanks
A MasterPage is implemented as a Child Control of your Page. You should be able to access it using Page.Session from the MasterPage.
I just noticed you may have been asking is where to assign the property, rather than where to declare it. So, if you're asking what is the best practice as far as where to initialize Session data, then the answer is going to be the PostAcquireRequestState event of the HttpApplication class. You can declare this in either your Global.asax, or wire it up with a custom HTTP module.
This sort of strategy works well and allows for session data access from anywhere in the site in a strongly typed manner.
public static class SessionData
{
private const string ENCRPYTED_QUERY = "ENCRPYTED_QUERY";
public static string EncrpytedQuery
{
get
{
if (HttpContext.Current.Session != null)
return HttpContext.Current.Session[ENCRPYTED_QUERY] as string;
return null;
}
set
{
HttpContext.Current.Session[ENCRPYTED_QUERY] = value;
}
}
//add more down here...
}
I created a user control. It contains one textbox. can I control this from parent web page.
Add the following property to your user control:
public string SomeValue
{
get
{
return txtSample.Text;
}
set
{
txtSample.Text = value;
}
}
And if you want to get or set the user control's textbox value from the page that contains the user control, just do the following:
MyUserControl.SomeValue = "Hello from page";
lblTest.Text = MyUserControl.SomeValue;
Where "MyUserControl" is the ID of the user control in the containing page.
Note: Since the TextBox control handles its Text property in the ViewState on its own, you don't have to explicitly handle it for this property.
Just define some public method or property in the user control and you can access it successfully. For example:
In UserControl1.ascx.cs:
public void DoSomething()
{
//Do something here from UserControl
}
In the parent:
MyInstanceOfUserControl1.DoSomething();
I have an ASP.NET webform where I initialize an array with a list of controls on the page like this
FileUpload[4] = new FileUpload[4];
public myclass()
{
fileUpload[0] = FileUpload1;
fileUpload[0] = FileUpload2;
...etc
}
I then use these in the page load and they are all null. This seems a strange behavior to me. Can someone elaborate and explain? I can understand that they are null in the constructor but why should they be null when used in the page load.
They are null because the controls haven't been created yet.
Take a look at the ASP.NET Page Life Cycle Overview and the Init event.
If you want to add controls "manually", you need to do this in OnInit() so they can be given state from the LoadViewState() call that will happen just after OnInit().
If you don't know how many controls you need to add, because it's dynamic somehow, you can override LoadViewState and SaveViewState. See this example(written without Visual Studio):
public class MyPage : Page
{
class State
{
numberOfControls int
otherState object
}
override void LoadViewState(savedState object)
{
var myState = (State)savedState;
SetupMyControls(myState.numberOfControls);
base.LoadViewState(myState.otherState);
}
override object SaveViewState()
{
return new State
{
numberOfControls = GetNumberOfMyControls(),
otherState = base.SaveViewState()
};
}
}
This is a common need I have on every page:
if (session["LoggedIn"] == null || ((bool)session["LoggedIn"] != true))
....//user is not logged in. return.
I was wondering, is there a way I can create a class "Helper" with a method signature bool IsLoggedIn() and call that method from a page so that automatically it can check if the page it was called from has the session["LoggedIn"] set to true? Something like this:
class Helper
{
public bool IsLoggedIn()
{
System.Web.UI.Page page = ***FindCallerPageSomeHow***();
if(page.session["LoggedIn"] == null || ((bool)page.session["LoggedIn"] != true))
return false;
return ((bool)page.HpptContext.Session["LoggedIn"] == true);
}
}
Ofcourse, I could try implementing an interface for each codebehind class, but thats repetitive. Also, I could pass in the HttpContext for IsLoggedIn, but that's a bit of clutter..
Any ideas? Is there a simple-to-implement pattern for this?
If you want to use this approach I would probably add a extension method on the session. But using formsauthentication is usually a lot easier.
Update
Btw, here is the extension method:
public static bool IsSignedIn(this HttpSessionState session) {
//Use the session to check if the user is signed in
}
Then you can use it like this:
if(Page.Session.IsSignedIn()) {
//Code
}
You could always have a static class in a library somewhere, but my favorite technique is simply to create your own Page class and add properties or override events there.
public class myPage : System.Web.UI.Page
{
public void myPage()
{
}
public bool IsLoggedIn()
{
System.Web.UI.Page page = ***FindCallerPageSomeHow***();
if(page.session["LoggedIn"] == null || ((bool)page.session["LoggedIn"] != true))
return false;
return ((bool)page.HpptContext.Session["LoggedIn"] == true);
}
}
Then in the code behind of your actual page, you would have
public partial myAspxPage : myNamespace.myPage
{
}
As an example, my page class usually contains a public property called ValidUser that contains pertinent user information (so I don't have to keep looking it up). If that value is null, then I don't have one. If it's not, then I have what I need. Then whenever I create a new page in my site, I just have it inherit my page class instead of the default.
EDIT: Added your method in for a little more clarity.
Why not put the code in the master page? That way any pages that need to be tested for the user being logged in can inherit from that master page and all is handled automatically. Otherwise, you're just repeating yourself in the code for every page.
I would create a base class called BasePage which would inherit from System.Web.UI.Page. I would then have the codebehind class inherit from BasePage.
In BasePage, you just add a method called IsLoggedIn(), and you can call it from anywhere within your code behind class.