aspx获取aspx.cs中的变量和方法

aspx.cs和aspx之间相互调用必须是同一个Web窗体。

1.aspx.cs文件

public int i = 0; 注:定义一个全局字段。

public string pub() 注:定义一个全局方法。
{
string s = "'方法'";
return s;
}

protected void Page_Load(object sender, EventArgs e)
{
for (int n = 0; n <= 100; n++)
{
i += n;
}
}

2.aspx文件

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script>
var i =<%=i%>; 注:调用aspx.cs里的i字段
var p =<%=pub()%>; 注:调用aspx.cs里的pub()方法
alert(p+" "+i);
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:Label ID="Label1" runat="server" Text=""><%=i %></asp:Label> 注:调用aspx.cs里的i字段
<asp:Label ID="Label2" runat="server" Text=""><%=pub()%></asp:Label> 注:调用aspx.cs里的pub()方法
</form>
</body>
</html>

原文地址:https://www.cnblogs.com/zhang1999/p/7232848.html