我有一种情况,我需要在c#asp.net中的单个.aspx页面的文件后面创建多个代码。实际上,我有一个完成大量编码的Web表单,并且我需要多个开发人员同时对其进行处理。我怎样才能做到这一点?
这是我尝试过的代码片段
1类MyPartialClass.cs
namespace WebApplication1
{
public partial class Default : System.Web.UI.Page
{
protected void PrintText(string pt)
{
Response.Write(pt);
//lblTest.Text = pt; //Can not access this label in partial class.
}
}
}
类2是Default.aspx.cs
namespace WebApplication1
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
PrintText("Hello World");
}
}
}
和我的HTML源代码
<%@ Page Language="C#" AutoEventWireup="false" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblTest" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
ASP.NET将始终在文件后面将您的代码生成为部分类
namespace WebApplication1
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
因此,如果您将定义partial
与关联,并将类保留在相同的名称空间下,则可以将这些代码隐藏在不同文件中。
编辑: Web项目
//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
}
}
}
我还没有修改任何其他生成的文件。我想提到的一件事是,Default.aspx.cs
已生成的文件是使用类名“ _Default”生成的。我将其更改为Default
,Visual Studio重构了包含该类定义的所有文件的更改,但该Default.aspx
文件除外,在该文件中我必须手动从Inherits="WebApplication1._Default"
进行修改Inherits="WebApplication1.Default"
。
编辑2:
我一直在搜索互联网,根据http://codeverge.com/asp.net.web-forms/partial-classes-for-code-behind/371053,您尝试做的事情是不可能的。在http://codeverge.com/asp.net.web-forms/using-partial-classes-to-have-multiple-code/377575中详细介绍了相同的想法。如果可能,请考虑从网站转换为支持您正在尝试实现的目标。这是有关如何执行此转换的演练:http : //msdn.microsoft.com/zh-cn/library/vstudio/aa983476(v=vs.100).aspx
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句