![](/img/trans.png)
[英]How do I add CSS styles to an ASP.NET UserControl from the code-behind?
[英]asp.NET Web App, how do I share classes with all code-behind files?
我知道这个网站并不总是欢迎超级基本的新手问题,而且我担心这些模组可能会像仓鼠上的鹰一样猛扑到这篇文章上,但我真的被困住了。
我继承了用 C# 编写的 asp.NET 应用程序。 它不是一个项目,也不与解决方案相关联; 它只是 aspx 文件及其关联的 aspx.cs 代码隐藏文件的集合。
这是一个编程混乱,我正在尝试使用 class 对象重写它(我正在自学这个)。 我的 class 对象工作正常,但我必须将类放在每个代码隐藏页面中; 这显然是不对的。
将我的类放在单个 myClasses.cs 文件中并让我的其他 aspx.cs 代码隐藏文件使用它们的最直接方法是什么? 我已经查看了一百个不同的帖子,但我似乎无法解决这个非常简单的问题。 其中许多涉及解决方案中的项目,但正如我所说,这个应用程序只是一个没有项目的文件集合。 我试图在终端中“构建”(我正在使用 VSCode),但它说它找不到项目文件。
看了几十篇文章,这似乎是一个笼统的答案。 这是来自这里: https://www.codeproject.com/questions/242165/csharp-asp-net-sharing-methods-between-classes
一般形式为:
My class:
public class BasePage : System.Web.UI.Page
{
public int YourMethod(string str)
{
int someNum = 1;
return someNum;
}
}
然后在其他代码隐藏页面中,访问它:
YourMethod("something")
有时 Intellisense 似乎在我编码时看到 class,但 web 页面显示它看不到代码 object。
任何帮助表示赞赏。
好吧,您创建的简单 class - 不在特定页面的代码中?
只需将 class 添加到项目中 - 创建一个名为 MyCode 的文件夹。
The only issue is the class in question a class that you are required to create a new instance of to use in code, or is the class just some helper and utility routines - that can be a static class, since it just a code library you想到处使用。
因此,右键单击项目探索,然后选择添加 asp.net 文件夹:
例如这个:
现在,如果 app_code 已经存在,那么您不需要创建该文件夹,并且可以简单地将您的类添加到该文件夹 - 它们将是全局的。
所以,然后这个 - 右键单击 app_code,并添加一个 class:
例如这个:
到那时,您可以创建一个 class - 一个 static 一个,用于您的流派例程和我们拥有的代码的大杂烩。 还有可能混合了属性和代码的类——你当然必须创建一个实例。
所以,我有一个系统范围的 class - static - 真的相当于我一直需要和使用的一般例程的代码模块。
因此,例如,我们经常必须获得一个数据表——无需一遍又一遍地重新键入那种代码。
所以,在我的代码“通用”class 中,我有这个(以及更多)。
public static class General
{
public static DataTable MyRst(string strSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(strCon()))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
cmdSQL.Connection.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
所以,现在在 web 页面上,我可以说像这样放入网格视图:
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
现在我的页面加载代码是这样的:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
void LoadGrid()
{
string strSQL =
@"SELECT FirstName, LastName, HotelName, Description
FROM tblHotelsA
ORDER BY HotelName";
DataTable rstData = General.MyRst(strSQL);
GridView1.DataSource = rstData;
GridView1.DataBind();
我们得到了这个:
因此,由于它是 static class - 那么我不必在使用它之前创建该 class 的实例 - 它只是一堆方便的代码例程的全局代码 - 它们是全局的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.