c# – Create partial classes in Asp.Net – Education Career Blog

I have a small web application.

This is what I want to do: Create partial classes to split up a code behind file.
Why am I not able to create partial classes directly?

If this is the codebehind file:

using System;
using System.Configuration....


public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Test();
    }
}

And also create this class:

public partial class _Default
{
    public void Test()
    {
    }
}

I get an error message, Test doesn’t exists in current context.

Why is this?

I get everything to work if I create a couple of partial classes which inherits from System.Web.UI.Page and then inherit my codebehind file from this class (the result of the partial classes). Is this the only way?

Has is something to do with that the codebehind and the aspx-page is dynamically compiled into a class?

Would appreciate if anyone could answer my problem. Things are working out right now but I would prefer to create the partial classes at the same “level” as the codebehind and avoid to use inheritance.

Thank you /John

(note that I have underscore in front of both classes but only one is visible in the preview, I don’t know why..)

,

1) Put your partial classes in the app_code directory (I’ve never tried this)
2) Convert your application into a Web Application Project from a Website Project

A WAP is more like a dll or winforms project, which is compiled before runtime (although the ui can be updatable) and puts classes in namespaces. Website projects are compiled using the aspnet_compiler which operates differently (e.g., dynamically named assemblies) than the standard compiler.

,

They should be on the same namespace, if they dont its not going to work.

Best Regards!

,

Okey. Well it wasn’t a namespace problem but thanks for that suggestion.

Everything worked fine when I created a web application instead of a website, thank you very much.

By default when I start new projects I always select create new website, I have never had any problem with this before.

So of course I’ll have to ask what is the difference except the one mentioned above?

Will there be any drawbacks with always going with web application projects instead of website projects?

Thank you /John

,

The answer locates at default.aspx 1st line:

Language="C#" CodeBehind="Default.aspx.cs" ...

will set every partial class working.

Instead,

Language="C#" CodeFile="Default.aspx.cs" ...

will lead partial class to wrong.

However, in vs2017 old-style-webForm you can only use CodeFile, so you have to try another way: create one file ..\WebF8\App_Code\Class3.cs with content as:

     public static class Class3 {
            public static int gg3=33;
     }

then you can see Class3.gg3 in default.aspx.cs correctly.
Be careful, this Class3.cs file must be in \App_Code folder.

Leave a Comment