I have a.master and b.aspx .
i have some functions in my aspx page.
how to access that functions in a.master page.
thank you
Let's say, you want to call Foo from b.aspx from a.master. So first thing is that you have make the method internal (or public) and then you can use code such as below in master page is call that method.
var page = (b)this.Page;
page.Foo();
Note that b will be the code behind class name in b.aspx. Note that above code will fail if you use another page c.aspx and use the same master a with it. Generally, I will say that invoking page specific functions from master does not make sense unless functions are present in some base page class and in such case you should be casting to that base page class.
Edit: More elaborate example as requested by Asif:
Consider your content page b.aspx such as
<%# Page Language="C#" MasterPageFile="a.Master" Title="Page B" AutoEventWireup="true"
CodeBehind="b.aspx.cs" Inherits="YourProject.b" %>
And in code behind file (b.aspx.cs), you have a method Foo such as
namespace YourProject
{
public partial class b : System.Web.UI.Page
{
void Foo(string someParameter)
{
Label1.Text = someParameter
}
...
}
}
Now in code behind (a.master.cs) of a.master page
namespace YourProject
{
public partial class a : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
b contentPage = (b)this.Page;
contentPage.Foo("Hello");
}
....
}
}
Of course you can make the method in b.aspx be public to call it in a.master. However I suggest you consider your design carefully. Because it's really weird just like that you call a method of a child class from its parent class (even though it's theoretically possible). Before your modification, ask yourself:
Is it necessary to call this method in the master page? If yes, do I have a better place to put the method?
As others have said, it's possible to do this. However, it's an odd way of doing things. You are probably going to be better off doing whatever you want to do in a different way. The whole idea of a master page is that it "wraps" many kinds of content pages. What if you content page doesn't have the function you want to call?
You could make sure all your content pages have the function, but then why not just put it in the master page?
Perhaps if you descired what you wanted to do a little better, we could advies you on a better way to handle things.
To access, either:
Make that method a static method.
Move your code in App_Code folder.
Move your code out of your web project, into some generic assembly and use that as a reference.
Related
I have created user control, in that user control i have one method and I want to call this method in .aspx. I have registered this user control in aspx
For example:
Below is method in user control.
public void SetGridData()
{
}
I want to call above method in .aspx.cs file.
How can we call this method?
Somewhere in the ASPX page's code you should have a reference to the user control object. For example, if the user control is called MyUserControl then somewhere at the class level for the page (possibly in a separate partial class designer file) should be:
protected MyUserControl myUserControl1;
or something similar to that. That's the instance of the user control for the page's class. The page life cycle should instantiate it by the time Page_Load is reached, so from then on you can use that object:
myUserControl1.SetGridData();
If this is purely an example, then you can call methods in codefiles with the following syntax:
<%= SetGridData(); %>
However, just be aware of the notes I put in the comments above.
I want to make page Load function in a class. in fact I don't want to use code behind, I want to create a class and define all of my functions (like page load and button clicks ,...) in it .
how I do it?
You can make your class inherit from System.Web.UI.Page, and set your aspx file's Page directive to inherit from your class.
But that's basically the same thing as having a code behind page.
Try ASP.NET webforms MVP pattern that allows to do it more object oriented way but you still need to handle page_events. If you need completely stateless, use ASP.NET MVC.
Create a class say pagebase and inherit you codebehind page with this class now the class code is below.
public class PageBase :System.Web.UI.Page
{
public PageBase ()
{
//
// TODO: Add constructor logic here
//
}
protected override void OnLoad(System.EventArgs e)
{
CheckSecurity();//any function you want to call before
base.OnLoad(e);
}
public virtual void CheckSecurity()
{
//your logic here
}
}
Now this class load function will run before the codebehind page page load runs. Let me know if you have any questions
I've a Master Page which contains a DropDownList. I've a function for binding the list in the master and it works fine.
My problem is: How will I call that Master Page function from a form, which is not the child of the above master page
See article here.
Here is something nice that comes from the new compilation model in ASP.NET 2.0. Let’s say you add a custom property to a master page code-behind file like so:
partial class otcMaster : System.Web.UI.MasterPage
{
public string FooterText {
get { return Footer.Text; }
set { Footer.Text = value; }
}
}
You can get to the master page for a web form using the inherited Master property, which returns a MasterPage reference. To get to a property defined in otcMasterPage though, you might think you need to use a cast.
((otcMaster)Master).FooterText == "foo"
Casting to a derived type is just a part of life when using frameworks and statically typed languages, but there is a better way. Use the # MasterType directive in the ASPX.
<%# MasterType VirtualPath="~/otc.master" %>
Now when ASP.NET codegens the page, it puts the following inside a partial class definition. Notice the Shadows keyword (that would be the new keyword in semicolon land [yeah, I’m experimenting with alternative languages]).
public new otc Master {
get { return (otcMaster)base.Master; }
}
The result is a strongly typed Master Page. We don’t need a cast, we can go right to the Master.FooterText property. Another way to do this is to specify a TypeName in the #MasterType directive.
Provide a public method in your MasterPage, then you need to cast the ContentPage's Master property to the appropriate type:
public void DataBindDropDowns()
{
// ...
}
Then you can call it from your ContentPages in the following way(assuming your masterpage's type is called SiteMaster:
((SiteMaster)this.Page.Master).DataBindDropDowns();
Edit:
...which is not the child of the above master page
I assume that means it's no a ContentPage of that Master, am i right?
Then it's not possible to get a reference to the master except when:
The master's method is static, what is impossible in this use case since you want to bind controls on the master
You have a reference to a page which master is of that type, but again impossible since the current HTTP-Handler is another page which does not use this master
Note that the master page actually is a child of a ContentPage and will be merged with it. It's not possible to get a reference to an object that does not exist!
From MSDN:
Note that the master page becomes a part of the content page. In
effect, the master page acts in much the same way a user control acts
— as a child of the content page and as a container within that page.
You need to refer to MasterPage property, cast to your master page type and invoke your method.
((MyMasterPage)this.Master).MyBindingFunction();
Put this in your page code (where MyMasterPage is your master page object):
MyMasterPage masterPage = (MyMasterPage) this.Master;
masterPage.MyBindDropDownListFunction(); // Replace with your public function name
If you're making it very frequently, you can create a BasePage derived from System.Web.UI.Page, and use it as the bage page for your forms.
There you can add a property of the type of your master page, that will give you acces to all public members of the Master Page.
If you master page class is Site1, you could do something like this in your BasePage.
public class BasePage : System.Web.UI.Page
{
protected Site1 Site1Master
{
get { return Master as Site1; }
}
}
Then in the pages where you need to acces the methods of the master page replace:
public partial class DefaultPage : System.Web.UI.Page
with
public partial class DefaultPage : BasePage
Then you'll have the property Site1Master available in the pages, and you can use any of its public members like this:
Site1Master.MyBindingFunction(...);
You can also add any other desired functionality in your BasePage.
NOTE: If you want to make sure that the property isn't null in the pages, you can add a check to see if the page has the Site1 master, like this:
protected Site1 Site1Master
{
get
{
if (!(Master is Site1))
throw new Exception("This page doesn's have Site1 as master page");
return Master as Site1;
}
}
For accessing the members of a Master page there's a Master property exposed on Page Content.
First you've to specify the # MasterType directive :
<%# Page masterPageFile="~/MasterPage.master"%>
<%# MasterType virtualPath="~/MasterPage.master"%>
Then in the Master Page create a Public function and in your content Page you simply call
Master.MethodNameInMaster()
For better design use EventAggregator pattern. Create your custom event and handle it in Master Page.
I need to create a code that reads the QueryString and set a value on the Session and on the end of the page I need to clear the Session.
How can I make a code like this to run on all .aspx pages?
Two possibilities are:
Create a class that inherits from System.Web.UI.Page. Insert your code there and all your pages inherit from that class instead of System.Web.UI.Page.
Create a HttpModule
well as i see it you got 2 solutions
Use a master page and do it there
Inherit Page and use that as base class on all your pages
One question why must it be stored in a session? this will give your problems if the same user executes 2 pages at the same time (the first to finish will clear the sesson for the other page)
if you only need the data while the page runs you can just save it in a normal variable, else use the viewState!
Or just use Global.asax: http://en.wikipedia.org/wiki/Global.asax
Create a class that inherit from Page that you will use instead of Page.
Alternatively, you can use a MasterPage if your application design allows that.
By putting the code in a basepage and letting all your .aspx pages inherit from the basepage.
An easy way to include code that is part of all pages is to subclass Windows.Web.UI.Page, and have all your pages inherit from this new class, instead of Windows.Web.UI.Page. The new class can register for page events, independently from each individual page.
Another option, if you don't want it to be part of each page, and you want to ensure that it runs even if a developer doesn't inherit your new page subclass, is to write an HTTPModule. This hooks into the ASP.NET processing pipeline, and you can trigger off pipeline events, such as authentication or displaying pages. You can write an HTTPHandler and run it out of the pipeline as well. (All pages implement IHTTPHandler, somewhere up the chain.)
I used the method of writing a class to inherit from System.Web.UI.Page. However, I did not find the implementation of this method to be obvious. Here is the code that I eventually wrote:
public class BasePage : System.Web.UI.Page
{
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
// Code here will be run when any page loads that inherits from BasePage
}
}
}
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.