How to create multiple code behind file for .aspx page

时光毁灭记忆、已成空白 提交于 2019-12-05 16:01:47

ASP.NET will always generate your code behind files as partial classes

namespace WebApplication1
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
    }
}

You can therefor separate the code behind in different files, if you pertain the definition as partial and keep the class under the same namespace.

Edit : The Web Project

//Default.aspx
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master"     AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:Label ID="lblTest" runat="server" Text="Label"></asp:Label>
</asp:Content>

//Default.aspx.cs
namespace WebApplication1
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            PrintText("Hello World");
        }
    }
}

//MyPartialClass.cs
namespace WebApplication1
{
    public partial class Default
    {
        protected void PrintText(string pt)
        {
            Response.Write(pt);
            lblTest.Text = pt;    //lblTest is accessible here
        }
    }
}

I haven't modified any other generated files. One thing I like to mention is that the Default.aspx.cs file that has been generated was generated with the class name "_Default". I have changed it to Default and Visual Studio refactored the change across all files that contain a definition for that class, except the Default.aspx file, where I had to manually modifiy from Inherits="WebApplication1._Default" to Inherits="WebApplication1.Default".

Edit 2:

I kept searching the internet, and according to http://codeverge.com/asp.net.web-forms/partial-classes-for-code-behind/371053, what you are trying to do is impossible. Same idea is detailed at http://codeverge.com/asp.net.web-forms/using-partial-classes-to-have-multiple-code/377575 If possible, consider converting from Web Site to Web Application, which supports what you are trying to achieve. Here is a walkthrough on how to perform this conversion: http://msdn.microsoft.com/en-us/library/vstudio/aa983476(v=vs.100).aspx

You need to set up a source safe server in order to that, like Team Foundation Server.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!