创建于codebehind隐藏字段,并通过客户方的JavaScript访问它 [英] Creating a hidden field in codebehind and accessing it via clientside javascript
问题描述
我要以编程方式添加一个隐藏字段一个asp.net页面,阅读并通过JavaScript改变它。到目前为止,我的code未能在读添加隐藏字段。
I want to add a hidden field programmatically to an asp.net page, read and change it via javascript. So far my code fails at reading the added hidden field.
下面是一个简单的例子:
Default.aspx的:
Here is a simple example: Default.aspx:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<body>
<input type="hidden" id="myHiddenField1" value="blub" runat="server" />
<button onclick="myFunction()">click me</button>
<script>
function myFunction() {
var testVar = document.getElementById("myHiddenField1").value; //works: field defined in aspx page
var testVar2 = document.getElementById("myHiddenField2").value; //fails, Object required: field defined in codebehind
alert(testVar);
}
</script>
</body>
</html>
Default.aspx.cs(包括ommited):
Default.aspx.cs (includes ommited):
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Page.RegisterHiddenField( "myHiddenField2", "bla!" ); doesnt work either
Page.ClientScript.RegisterHiddenField( "myHiddenField2", "bla" );
}
}
我收到的错误是:微软JScript运行时错误:所需的对象。如果我添加警报(testVar2)并忽略该错误消息框显示未定义。
The error i receive is: Microsoft JScript runtime error: Object required. If i add an alert(testVar2) and ignore the error the message box displays "undefined".
[/编辑]
[/ EDIT2]
越夏了我的问题:如何在codebehind创建一个隐藏字段,以便自己能得到并从JavaScript设置呢?
Summering up my question: How do i create a hidden field in codebehind so i can get and set it from javascript?
推荐答案
的主要问题是,下面的一行丢失在aspx页面:
The main problem was that the following line was missing in the aspx page:
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
在codebehind从未执行。
The codebehind was never executed.
这篇关于创建于codebehind隐藏字段,并通过客户方的JavaScript访问它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!