用Google搜索并尝试了我找到的所有回复,但无法找到正确答案。
尝试简单地将代码从代码隐藏(C#)传递到aspx(更具体地说是javascript变量)
代码背后:
public partial class _Default : System.Web.UI.Page
{
public string greetings = "hello";
protected void Page_Load(object sender, EventArgs e)
{
}
}
ASPX:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>My page</title>
<script>
var greeting2;
function GetGreeting()
{
greeting2 = <%=greetings%>;
}
</script>
</head>
<body>
<form id="form1" runat="server">
</form>
</body>
</html>
我尝试在后面的代码中使用get方法而不仅仅是公共变量,但这具有相同的效果。我也试过&lt;%= this.greetings%&gt; (有和没有=符号)。什么都行不通。帮助!
答案 0 :(得分:1)
将字段更改为属性:
public string greetings { get; set; }
您现在应该能够在aspx页面上访问它,因为ASPX 页面基本上都是从代码隐藏类继承。
答案 1 :(得分:0)
在_Default.aspx.cs的Page_Load中(代码隐藏):
ScriptManager.RegisterStartupScript(this, this.GetType(), "", "GetGreeting(" + greetings + ");", true);
然后在_Default.aspx页面
<script>
var greeting2;
function GetGreeting(greetings)
{
greeting2 = greetings;
}
</script>
答案 2 :(得分:-1)
public partial class WebForm4 : System.Web.UI.Page
{
public string greetings = "Hellooooo";
protected void Page_Load(object sender, EventArgs e)
{
}
public string Method()
{
return greetings;
}
}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script type="text/javascript">
var greeting2;
function GetGreeting()
{
greeting2 = ('<%=Method() %>');
alert(greeting2);
}
window.onload = GetGreeting;
</script>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>