我正在从PHP迁移到ASP.NET/C#.到目前为止一直很好,但我不明白如何在ASP.NET C#类页面中实例化一个类.
例如,我有login.aspx:
<%@ Page Language="C#" Inherits="Portal.LoginService" src="LoginService.cs" %>
<!DOCTYPE html>
<body>
<form runat="server" id="login" name="login">
<p>Username:</p><input type="text" id="username" name="username" runat="server" />
<p>Password:</p><input type="password" id="password" name="password" runat="server" />
<input type="submit" name="submit" OnServerClick="Post_Form" runat="Server" />
</form>
</body>
Run Code Online (Sandbox Code Playgroud)
LoginService.cs:
using System;
using System.Web.UI;
using System.Web.UI.HtmlControls;
namespace Portal {
public class LoginService : Page {
protected HtmlInputControl username, password;
public void Post_Form(object sender, EventArgs e) {
if (username.Value != "" && password.Value != "") {
//LOGIC HERE
//This doesn't work
CustomSanitize a = new CustomSanitize();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
CustomSanitize.cs:
using System;
namespace Portal {
public class CustomSanitize {
//instantiate here
public string sanitizeUserPass() {
return "logic here"
}
}
}
Run Code Online (Sandbox Code Playgroud)
换句话说,我想使用不同类中的方法和我使用ASP.NET C#设置的类.到目前为止,命名空间对我来说并不起作用.
谢谢你的任何意见.
如果我正确地为您服务,请将CustomSanitize命名空间包括在内:
namespace MyProject {
public class CustomSanitize {
//instantiate here
public string sanitizeUserPass() {
return "logic here"
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后换LoginService.cs行相同的命名空间.即
namespace MyProject {
public class LoginService : Page {
protected HtmlInputControl username, password;
public void Post_Form(object sender, EventArgs e) {
if (username.Value != "" && password.Value != "") {
//LOGIC HERE
//This doesn't work
//CustomSanitize a = new CustomSanitize();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
你现在应该有权访问 CustomSanitize a = new CustomSanitize();
您还可以创建更多名称空间来拆分项目.即namespace MyProject.Helper包装所有辅助函数,然后只需添加using MyProject.Helper到.cs您希望使用类的文件的顶部.
编辑:
请注意,在命名空间中向项目/包装类添加命名空间时,您需要通过该命名空间using或直接引用它们MyProject.LoginService.这必须在页面上完成aspx,ascx使用@ Page declaration.
| 归档时间: |
|
| 查看次数: |
9171 次 |
| 最近记录: |