Search code examples
asp.net.netconstructorcode-behind

Use Constructor in ASPX Page (No Codebehind)


Can I implement a constructor in an ASPX page without a Codebehind file?

I have a page "test.aspx" and I try to include a constructor:

<%@ Page Language="C#" %>
<script runat="server">
    public dd_prop_test_aspx() : base() { /* Do stuff */ }
</script>

But, the runtime compiler gives me an error:

CS0111: Type 'ASP.test_aspx' already defines a member called 'test_aspx' with the same parameter types

Line 558:        [System.Diagnostics.DebuggerNonUserCodeAttribute()]
Line 559:        public test_aspx() {
Line 560:            string[] dependencies;

Can I specify a directive to not generate a constructor automatically (as it appears that the compiler does)? Or, do I have another way of working around this?

In the end, I would like to set variables in the class before Page_PreInit, so if a workaround exists without using constructors, that would work, too.


Solution

  • Although you cannot redeclare the constructor, you are free to override any method from a <script runat="server"> tag, as long as you don't override it in the code beside as well. And, you can also add page event handlers (same restrictions apply) like Page_PreInit.

    As you can use both the page event and the override at the same time, you might be able to inject code in advance:

    <script runat="server">
        void Page_PreInit(object sender, EventArgs e) 
        {
            Response.Write("First?");
        }
    
        protected override void OnPreInit(EventArgs e)
        {
            base.OnPreInit(e); // implicitly calls Page_PreInit
            Response.Write("Second!");
        }
    </script>
    

    So if you are using Page_PreInit in your code behind as a page event handler, you can use the override of OnPreInit in your .aspx and put your code before the call to base.OnPreInit(e).

    If you're overriding OnPreInit in your code behind, you can declare a Page_PreInit in your .aspx and it depends on where you call base.OnPreInit(e) before your code behind logic or after.

    In other words: you have full control over when it happens.