Alex
Alex

Reputation: 512

Using the same code behind file for multiple .aspx pages

We are developing a site inside a CMS that pushed files to our production server. If the .apsx pages created share the same code behind file, will this cause a problem?

Upvotes: 6

Views: 6581

Answers (3)

sll
sll

Reputation: 62504

I would suggest to avoid such design, so each page should has own code behind file. Also take a look at the following ASP.NET features whcih can simplify sharing of common layout and behaviour across the web pages:

  • Master pages (.master), basically multiple pages which has the same layout could use a shared master page which provides the common layout and supporting code behind logic. Moreover - You can switch master pages in runtime and master pages could be nested, so Master Page could be placed inside of an other Master Page, this gives you a much of freedom and flexibility to design your web application layout and separate responsibilities as well.
  • User Controls (.ascx), it worth to separate concerns and split page by a set of controls, for instance, it could be LoginControl.ascx,, AdControl.ascx, SearhcControl.ascx, so you keep a code of page clean and each control provides specific functionality and own layout.
  • Inheritance, so basically set of pages have the same base class which inherited from the Page class (I would not suggest use this approach massively, one base page it is enough)

    You may use other common development techniques like dependency injection to share code across multiple pages, this depends on particular case and business goals which were considered under the hood.

Upvotes: 2

Bazzz
Bazzz

Reputation: 26922

Why don't you let both pages inherit from the same class?

public class MyPage : System.Web.UI.Page
{
   // common logic that both pages should have

   protected void Page_Load(object sender, EventArgs e)
   {
   }
}

public partial class PageA : MyPage
{
   // specific logic for page A
}

public partial class PageB : MyPage
{
   // specific logic for page B
}

Upvotes: 10

Peter Olson
Peter Olson

Reputation: 142921

Yes. It is technically possible, but it is not a supported way of using ASP.NET and there will likely be gnarly difficulties with it.

You should use User Controls or AppCode instead.

Upvotes: 3

Related Questions