asp.net - variable pass between ascx and page - c#

Have any ways to keep a variables (object) in a page scope? I need pass some object from master page to all ascx files. Normally, i passing by using a method or structure with parameters. But now im asking another way to do this. Store it in session is a bad idea because my object should exists in a page scope only.

One way is to set up properties in your user controls. You have access to read and set these from all pages that implement them.

Another alternative is to store the shared object(s) in the HttpContext.Items collection.

You could expose your variables a public properties of the master page:
public string MyVariable { get; set; }
then access them from the user controls by referencing the master page, and casting to its specific type:
((MyMasterPageType)Page.Master).MyVariable

So you have masterpage, user controls and the page itself.
The page is the container for the masterpage and the user controls, hence it's the only one that 'knows' the 2 parties. So I'll suggest (if you haven't) you have the page instance to facilitate the object/variable passing amongst them.

If your variable's value is going to be changed on per page basis then i would recommend you to write that code in base page (or user control) and inherit all the page (or usercontrol),if the values are going to be similar for all pages(or user control) you can use cache object as well.
In a more better approach if you feel you can even create one helper class and call it from your base page (or user control), so you can separate variable assignment code from your page.

Related

Error using 'this' in a cs page trying to access control

I have a page called test.aspx with test.cs.
However, i want to access my control called mbResult
Which is my custom messagebox control, from a sepearate CS page.
I know many people have asked this question and i have found that this is a method to access my controls.
MessageBoxControl mbox1 = this.FindControl("mbResult") as MessageBoxControl;
But I keep getting this error
Error 5 Keyword 'this' is not valid in a static property, static method, or static field initializer
Any ideas on how to access this control all i am trying to do is make it visible.
Thanks
You need to move the code into a non-shared method. You need to be operating in an instance of the page.
Update for clarification in comments
Unfortunately, your application is going to need some restructuring.
If the messageboxcontrol is shown in a new window, then you will need to pass the value from your source page to the new window in the query string.
However, if you want the messagebox control to be displayed on the source page, then you will need to convert it from a page to a UserControl, add a reference to the user control to your source page, and then add an instance of the usercontrol directly to the source page.
Statics don't have instance-based contexts, so using this is not applicable. You'll need a reference to the control for which you want to use .FindControl (possibly by passing it as a parameter).

Changing displayed data from a static method in ASP.NET

I have two user controls that sit on a page which determines which should be displayed. The user controls generate some html that is passed into an asp:literal and subsequently manipulated via javascript. It is done this way due to the lack of a suitable control that I am allowed to use on the project.
When a user clicks a view change button, a WebMethod is called on the main page (the one that holds the controls) from the control's javascript. From here, a static method on the control is called. The control then needs to regenerate the html and place it into the asp:literal for the view change to be complete.
My problem is that I am in a static method on the control's page, and have no access to the non-static genorateHtml function. I have tried a singleton pattern with no success (this could have been due to improper implementation). Any ideas on how to make this call? THANKS!
I used to hit similar issues at with one of the projects i worked on. The solution we ended up adopting was implementation of System.Web.UI.ICallbackEventHandler with partial rendering to return just the needed content depending on arguments. ICallbackEventHandler runs in the page lifecycle.
The only trouble we had then was performance issues relative to implementation which posts back the whole form instead of just the arguments you want.
Maybe the best way for you would be through this method in which they render the control from a static method. That would probably suit your needs.
Hope this helps!

Using EF Object as member of Master Page within Pages

If I've got a setup where my master page has a member which is an EF generated object, and I want to use this member then within the page itself (but have need for it within the master page as well).
Currently I've got a using loop within the Master Page Page_Init event to establish the member. However if then I try to get any properties of this within the Page I get an error about "The ObjectContext instance has been disposed...", which is fair enough (It is within it's own using loop, however that's a different OC instance, so it's throwing this error.)
What's the best/preferred way around this situation? Is it to open the Object Context within the MasterPage pre_init event, and then dispose of it during the Page_Dispose event of the Master Page, or use a second OC Instance in the Page, and just pull a local version of the EF object by checking it's ID against the Master Page's object ID?
Thanks, Psy
Can't you create a POCO when you load the master page and make it a protected property which your derived pages can get access to. Results in 1 trip to the database.
It's best practice not to use the Object Context in your UI layer to begin with. You should a business/data access layer to broker the communication with the database.

New to C# and trying to use a global variable

Is it possible to use global variables in C#? I'm coming from mainly a PHP background so variables are either accessible everywhere or just a global definition away.
My main issue is I have a User class that I built myself to wrap around the current users table on my company's database. I am defining it in the MasterPage but can't seem to access it from the actual pages (I don't know if there's a better word to describe them but they are the pages that inherit the styles and format from the MasterPage)
Any general tips or implementation practices for me?
EDIT: here's some code snippets of what I'm trying to do:
Site.master.cs
public partial class SiteMaster : System.Web.UI.MasterPage
{
public User user = new User();
}
logout.aspx
<%# Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="logout.aspx.cs" Inherits="logout" %>
<%# MasterType virtualPath="~/Site.master"%>
logout.aspx.cs
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
User user = Master.user;
}
}
No, it is impossible. It is possible to create singletons or public static classes, but this is bad practice.
C# was designed for object oriented programming. If you haven't written programs using object oriented paradigm before it can be a bit hard to switch to it in the beginning. OOP (http://en.wikipedia.org/wiki/Object-oriented_programming) is built on three main concepts: inheritance, polymorphism and encapsulation.
You can defined classed apart of the pages/masterpages, it is good practice to define them in the App_Code folder.
Have a public static class and declare public static member variables.
That's what I do when I need some globals, though I try to avoid using them when I can.
If Page is inheriting from MasterPage, then make User property protected in MasterPage and it will be visible to Page.
The Master page class can be accessible to the pages that use it by setting the MasterPageClass in your .aspx page like so:
<%# MasterType TypeName="MyTypeName" VirtualPath="~/MasterPageName.master" %>
It sounds to me like you may just need to put your code in a slightly different place. A typical User class would be accessible to your project through a stand-alone class, and not bundled into a master page or a master type.
I might suggest that you add your User class into a new classfile in the /AppCode directory of your project instead, (User.cs). That would let you have access to it from your pages without having to muck with the MasterType.
See my answer to this question. Non-static class-level variables do no persist once the response is sent to the browser. This is because each Page object is going to be a new instance of the class, not the same one from your last request.
Use the "Session" property instead as I show in the link.
Is your problem, from your page, get to data stored in the masterpage (assuming we're talking about the ASP.Net MasterPage mechanism here)?
If so, you should look at strongly-typed access to masterpages. Basically, what you do is create a public property in your MasterPage class. Then, in your Page, declare the MasterPageFile and MasterType, like this:
public partial class MasterPage
{
public User CurrentUser{...}
}
In your page aspx, declare to use the masterpage and which master type to use.
<%# Page masterPageFile="~/MasterPage.master"%>
<%# MasterType virtualPath="~/MasterPage.master"%>
You will then be able to access the property from within your page class like this:
var user = Master.CurrentUser;
Then, for the question on where to initialize the CurrentUser object, look at the list of page lifecycle events. As you can see, MasterPage.Init fires before Page.Init and MasterPage.Load fires before Page.Load. You can use either MP.Init or MP.Load to make sure the data is ready for when the page events fire, though Init is preferred.
There are at least a couple different ways to achieve what you want:
Use the Application object - It can be used to store things globally and is part of ASP.Net.
Use static classes - This is another option for creating a singleton.

How to reference a Master Page from a user control?

I'm looking for a way to (preferably) strongly type a master page from a user control which is found in a content page that uses the master page.
Sadly, you can't use this in a user control:
<%# MasterType VirtualPath="~/Masters/Whatever.master" %>
I'm trying to access a property of the master page from the user control and would rather not have to pass the property from the master page to the content page to the user control because multiple content pages use the same user control. One change, one place whatnot.
Try Page.Master.
Whatever whatev = (Whatever)Page.Master;
You'll have to make sure you add the proper using statements to the top of your file, or qualify the Master page type inline.
One potential gotcha is if this control is used by a different page whose master page is NOT the same type. This would only get caught at runtime.
Have you tryed Page.FindControl("name") on the usercontrol?
The best way to do it that I've found is actually to build a custom class that is based off of UserControl, give it a Master property with a get accessor that fishes through the this.Page.Parent until it stops encountering master pages (If you are nesting, this step is unnecessary otherwise) and then return that web control as the type of the master page you want to use. Then, when you add a new user control, change it's base class to the name of your custom class. The .Master property will be accessible and cast properly as the master page you want it to use.
In VB all I needed to do was change this:
Dim lAuthLevel As Integer = Master.MasterContact.AuthenticationLevel
to this:
Dim lAuthLevel As Integer = CType(Me.Page.Master, main).MasterContact.AuthenticationLevel
So all references of Master become Ctype(Me.Page.Master, typeofMaster)
Where is in this case the word "main" - get that from the declaration at the top of the master page. e.g.
So "main" in this case :)

Categories

Resources