asp.netwebformsnamespacesinline-code

How to define a namespace inside an ASP.NET page (inline code method)?


I insert the below code inside an ASPX file (MyTest.aspx). I don't want to use Code Behind.

<%@ Page Language="C#" %>

<script runat="server">
    namespace MyNamespace
    {
        class MyClass
        {
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write("Hello World!");
    }
</script>

But the following error occurred while browsing the page (MyTest.aspx):

Compiler Error Message: CS1519: Invalid token 'namespace' in class, struct, or interface member declaration

How to define a namespace inside an ASP.NET page (inline code method)?


Solution

  • it's obvious that asp.net won't allow it but have you tried an indirect way:

    <%@ Page Language="C#" %>    
    <script runat="server">
        class MyNamespace.MyClass
        {
    
        }
    
        protected void Page_Load(object sender, EventArgs e)
        {
           Response.Write("Hello World!");
        }
    </script>