Can two ASPX pages inherit the same code behind class? - c#

I'm just starting out learning ASP.NET. From what I understand, ASP.NET differs from old school ASP in that the logic code for a page exists in as separate file rather then being embedded in the ASP page. So when a user requests a page like ShoppingCart.aspx the server reads the directive at the top ...
<%# Page Title="" Language="C#" MasterPageFile="~/Styles/Site.Master" AutoEventWireup="true"
CodeBehind="MyShoppingCart.aspx.cs" Inherits="TailspinSpyWorks.MyShoppingCart" %>
This tells the server what file and what class in the file is associated with the page. The code behind class also has member variables that correspond to each control on the page, and provide a way for code in the code behind file to manipulate the controls.
First, do I understand this correctly?
Second, could a site be setup with two separate ASPX pages with identically named controls, which both had a directive pointing to the same file and class? Would you even want to do this? Both pages could have the same functionality but a different layout. I was thinking this could be a way to create separate "desktop" and "mobile" versions of a page with out duplicating content in the code behind files.
I guess ultimately what I'm wondering, is if there a way to define an abstract page? Say create an abstract page definition that says a page must have controls "cart_list", "total_lbl", but then be able to have multiple pages that inherit from this abstract page?

Yes, two pages can inherit from the same class. Like it can inherit from Page class directly and do not even have an associated .cs file (useful when you have a page which is not static, but which does not handle events or something which may require a code-behind class).
In practice, I think it's not a good idea to inherit several ASP.NET pages from the same class directly. This is not something common, so:
the code will be more difficult to understand and impossible to extend,
will be difficult to manage within Visual Studio, especially when it comes to events, controls, etc.
will cause much pain with existing/missing controls. See the detailed Guffa answer below.
If several pages of your website share the same logic,
make one class per page, and inherit those classes from a common parent class which will contain common methods and properties and which will inherit from Page class. You will obtain an extensive and easy-to-understand solution.
or create a masterpage if the case is a good candidate for a masterpage.

I'm just starting out learning ASP.NET. From what I understand, ASP.NET differs from old school ASP in that the logic code for a page exists in as separate file rather then being embedded in the ASP page
Classic ASP and ASP.NET differ in a lot of ways, the primary way being that classic ASP pages are (for the most part) a procedural, script-based, unmanaged code whereas ASP.NET pages are compiled, managed, and event-driven. Typically ASP.NET pages separate out the markup and the server-side code into two separate files, but this isn't a necessity. It is quite possible to put the server-side code in the .aspx page in a <script runat="server"> block.
the directive at the top ...
<%# Page Title="" Language="C#" MasterPageFile="~/Styles/Site.Master" AutoEventWireup="true" CodeBehind="MyShoppingCart.aspx.cs" Inherits="TailspinSpyWorks.MyShoppingCart" %>
tells the server what file and what class in the file is associated with the page. The code behind class also has member variables that correspond to each control on the page, and provide a way for code in the code behind file to manipulate the controls. First, do I understand this correctly?
Yes, you understand this correctly.
Second, could a site be setup with two separate ASPX pages with identically named controls, which both had a directive pointing to the same file and class?
Yes, you could do this.
Would you even want to do this?
Probably not. In fact, even if there are two separate ASPX pages that both inherit from the same base page there's nothing that forces them to have the same set of controls. In fact, they could have different controls and the page will render without error. (If you try to access a control in the code-behind that does not exist in one of the pages you'll get a runtime error.)
I guess ultimately what I'm wondering, is if there a way to define an abstract page? Say create an abstract page definition that says a page must have controls "cart_list", "total_lbl", but then be able to have multiple pages that inherit from this abstract page?
There's not (to my knowledge) a way to accomplish this. What might come close, though, is having a base Page class, which is a good practice to get use even if you don't have this particular scenario at hand. For more on creating and using base Page classes, see: Using a Custom Base Class for your ASP.NET Pages' Code-Behind Classes.
Happy Programming!

You might want to check this out, if you're using .NET 4.0. It describes Request.Browser.IsMobileDevice and Request.Browser.MobileDeviceModel.
You could put some logic into the code-behind, or the ASPX mark-up, to detect if you're running on a mobile device. That will allow you to have all the code in one file, but can select which HTML elements to display, etc.

Yes, and no.
You can use the same class for different pages, however the binding between the page controls and the variables in the class is not strict.
The control references will simply be assigned to the variables if they exist and have a matching type, but you can't make any restrictions that the page has to contain certain controls. You can however check if the variables has been assigned or if they contain null references the first you do in the code.
I have used the same class for different pages at some rare occasion, but it's not common practice. Usually there is little gain in doing this, and if you want to reuse code in the pages, you can put it in a class file and use it from the separate pages.

Related

C# Insert block of code to every aspx page

I'm having a web application project which is running .NET 4.0. I've plenty of .aspx page and now I would like to add in a block of script code to all the .aspx page header, for example Google Analytics.
I know there is a solution to do is add in every single page, but I would like to know is there any other's way to do this instead modify every single .aspx page?
*My header is not runat server
I got an idea to do but not sure it's work or not.
Get the page class in Global.asax
Get the output stream from the page class.
Insert the Google Analytics code in the HTML header.
I couldn't get the Page.Response in the Global.asax as I tried in the Application_PostRequestHandlerExecute & also Application_EndRequest. Does anyone know is this work and how it's work?
Thanks.
Use master pages. This is the ASP.NET way of putting the same content on multiple pages without repeating yourself.
All of our aspx pages code-behind classes inherit from the same base class, which allows us to inject standard client side elements (controls, script, etc) into every page using a single point of control.
Our design was implemented before the advent of master pages, but while it could possibly be converted to a master-page design, we have found this implementation to be extremely flexible and responsive to changing needs.
For example, we have two completely separate application designs (different skin, some different behavior) that is based off of the same code base and page sets. We were able to dynamically swap out banners and other UI and script elements by simple modifications to the base class in order to support this without having to duplicate every page.
Unfortunately, if you want the script to be in the head element, you will need to ensure that they are all marked as runat=server.
Our base class itself inherits from Page, so it can intercept all of the page's events and act on them either instead of or in addition to the inheriting classes (we actually have internal overrideable methods that inheritors should use instead of the page events in order to ensure order of execution).
This is our (VB) code for adding script to the header (in the Page's LoadComplete method):
' sbscript is a stringbuilder that contains all of the javascript we want to place in the header
Me.Page.Header.Controls.Add(New LiteralControl(sbScript.ToString))
If it is not possible to change the heads to runat server, you could look into ClientScriptManager method RegisterClientScriptBlock which places the script at the top of the page.
You can create a basic page with the header with the custom code such as Google analytics and have the other pages inherit from that. It will facilitate two things:
1) In case you ever want to change the custom code you will only have to do it in one place
2) No repetitive code hence more maintainable
I am trying to do the same thing on a legacy app that we're trying to decommission. I need to display a popup on all the old pages to nag users to update their bookmarks to use the new sites, without forcing them to stop using the legacy site (yet). It is not worth the time to convert the site to run on a master page when I can just plop in a popup script, since this whole thing is getting retired soon. The main new site uses a master page, which obviously simplifies things there.
I have this line in a file that has some various constants in it.
Public Shared ReadOnly RetirementNagScript As String = "<Script Language='javascript'> alert('[app name] is being retired and will be shut down [in the near future]. Please update your bookmarks and references to the following URL: [some URL]'); </script>"
Then I am inserting it in Global.asax, in Application_PostAcquireRequestState:
Response.Write(Globals.RetirementNagScript)
Hopefully this is useful to you; I still need to be able to present a clickable URL to the user that way, on each page of the legacy site, and JS alert doesn't do that for me.

No access to cooresponding .cs file in asp.net

The aspx page that I need to add code to has an aspx.cs file which was written by a company that has this aspx.cs file on their system (per contract) and I cannot modify/access.
Example: MyFile.aspx and no access file MyFile.aspx.cs
I need to use a label.text from the page in the control pages and also depending on IF ELSEIF statements it will call which of the different controls that it needs to execute.
What is a good way to do this when one does not have access to the aspx.cs file?
I have spent a couple days trying to find/figure out answers to this problem and keep running into problems.
You do have a strange situation here ;)
Here's one wild idea. You can change the Inherits attribute at the top of the .aspx file to substitue your own class instead.
Of course that means you have to rewrite all the logic behind the page -- or you can try to have your own class inherit the original one, but depending on visibility of original code this may not work.
Another option could be to use a decompiler to re-create all the source code of the web project from the compiled dll. But you may not be legally allowed to do that -- although I would point out that if you don't have the rights to use the code, you probably don't have the rights to use the .aspx either, even if you have access to them.

when do you need .ascx files and how would you use them?

When building a website, when would it be a good idea to use .ascx files? What exactly is the .ascx and what is it used for? Examples would help a lot thanks!
It's an extension for the User Controls you have in your project.
A user control is a kind of composite control that works much like an ASP.NET Web page—you can add existing Web server controls and markup to a user control, and define properties and methods for the control. You can then embed them in ASP.NET Web pages, where they act as a unit.
Simply, if you want to have some functionality that will be used on many pages in your project then you should create a User control or Composite control and use it in your pages. It just helps you to keep the same functionality and code in one place. And it makes it reusable.
We basically use user controls when we have to use similar functionality on different locations of an app. Like we use master pages for consistent look and feel of app, similarly to avoid repeating the same functionality and UI all over the app, we use usercontrols. There might me much more usage too, but I know this one only...
For example, let's say your site has 4 levels of users and for each user there are different pages under different directories with different access mechanisms. Say you are requesting address info for all users, then creating address fields like Street, City, State, Zip, etc on each page. That would be a repetitive job. Instead you can create it as an ascx file (ext for user control) and in this control put the necessary UI and business code for add/update/delete/select the address role wise and then simply reference it all required page.
So, thought user controls, one can avoid code repetition for each role and UI creation for each role.
Ascx-files are called User Controls and are meant for reusability and also for making complex aspx-pages less complex (lift out some part of the page). They could also be beneficial for something called donut caching, that is when you would like to cache a certain part of a page.
If you have a block of code+html that appears on several pages and is sort of independent of that page (say a block of latest news items), you could copy/paste the code to every page.
It is however better to put that code in its own block and just include that block on every page that needs it. That "block" is an ascx file.
One more use of .ascx files is, they can be used for Partial Page caching in ASP.NET pages. What we have to do is to create an ascx file and then move the controls or portion of the page we need to cache into that control. Then add the #OutputCache directive in the ascx control and it will be cached separately from the parent page. It is used when you don't want to cache the whole page but only a specific portion of the page.
ASCX files are server-side Web application framework designed for Web development to produce dynamic Web pages.They like DLL codes but you can use there's TAGS
You can write them once and use them in any places in your ASP pages.If you have a file named "Controll.ascx" then its code will named "Controll.ascx.cs".
You can embed it in a ASP page to use it:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="Controll.ascx.cs"%>
When you are building a basic asp.net website using webcontrols is a good idea when you want to be able to use your controls at more then one location in your website.
Separating code from the layout ascx files will be holding the controls that are used to display the layout, the cs files that belong to the ascx files will be holding the code that fills those controls.
For some basic understanding of usercontrols you can try this website

Inserting code from seperate source file (ASP.NET/C#)

How can I insert code into a page in ASP.Net from a seperate source file?
Say I have:
<%
Response.Write("hello world");
%>
How can I make it something like:
<% include(helloworld.cs) %>
I know how it work sin the header with the <%# and CodeFile= but I can't make it work for different spots of code. Is there a way ASP.Net handles this? I've tried googling but not sure what to search for.
Another option not mentioned yet is to use ASP.NET Master Pages. This is useful to have a consistent look and feel (and code behind) in the master page which extends to the child pages.
you could create a class library and add a reference to the library.
link that may help:
http://support.microsoft.com/kb/306575
You can use old-style Server-Side include tags like so:
<!-- #include virtual="/inc.inc" -->
But I do not recommend it. You should use User Controls instead; they give you more capability, and do not potentially expose server-side code if someone should happen to try to request them directly.
If you nevertheless decide to use includes like that, note that the content of the file is included in the ASPX/ASCX source code just as if you had typed it right in the main source file itself.
You can't shouldn't.
Instead, you should create a User Control.

Dynamic Page Creation .aspx

I have a IHttpModule to serve up .aspx page dynamically, this is so I can pack them into a DLL and drop it into an existing web site and serve up my pages.
I have a class MyPage derived from System.Web.UI.Page which has a .aspx, .aspx.cs and a aspx.designer.cs file.
When I try to instantiate the class I.e. MyPage myNewPage = MyPage(), all of the child controls are null...
I then attempt to render that page output using Server.Execute(myNewPage) in the BeginRequest event of the IHttpModule.
I know I can compile the page and use reflector to get the compiled class that's built out, but is there a cleaner way to do this?
Or even a better approach to what I'm doing?
Thanks,
Goosey
I don't think this is possible. You cannot just instantiate page like any other object. What you need "might" be a VirtualPathProvider.
I'm not sure it's the best solution, but you can embed all the aspx pages into your dll as assets. On request extract the aspx from the embedded resource and write to disk (if it hasn't already happened).
There may be a way to provide the aspx from the embedded resource without actually writing to disk, but I don't know for sure.
aspx has some intimate relationship with ASP.NET runtime. I do not think that instantiating it bu just calling constructor is a good idea. What you can do instead is to have an empty (standard) aspx and move your code to user controls - ascx
Those you can load dynamically using LoadControl method

Categories