【发布时间】:2012-02-22 01:49:37
【问题描述】:
来自这组 ASP.NET 演示代码:
http://msdn.microsoft.com/en-us/library/ms178209.aspx
在 ASP.NET 项目中的 VS2010 中,我收到错误消息:
“当前上下文中不存在名称'ListBox1'”来自引用 ListBox1 的 C# 源文件(第 35-37 行)。如果我在类中添加 ListBox1 的声明,错误就会消失,但是当我按 F5 运行它时,我会收到一条消息,指出 ListBox1 已经定义。我错过了什么?
ClientCallback.aspx.cs:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class ClientCallback : System.Web.UI.Page,
System.Web.UI.ICallbackEventHandler
{
// protected ListBox ListBox1;
protected System.Collections.Specialized.ListDictionary catalog;
protected String returnValue;
protected void Page_Load(object sender, EventArgs e)
{
String cbReference =
Page.ClientScript.GetCallbackEventReference(this,
"arg", "ReceiveServerData", "context");
String callbackScript;
callbackScript = "function CallServer(arg, context)" +
"{ " + cbReference + ";}";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
"CallServer", callbackScript, true);
catalog = new System.Collections.Specialized.ListDictionary();
catalog.Add("monitor", 12);
catalog.Add("laptop", 10);
catalog.Add("keyboard", 23);
catalog.Add("mouse", 17);
ListBox1.DataSource = catalog;
ListBox1.DataTextField = "key";
ListBox1.DataBind();
}
public void RaiseCallbackEvent(String eventArgument)
{
if (catalog[eventArgument] == null)
{
returnValue = "-1";
}
else
{
returnValue = catalog[eventArgument].ToString();
}
}
public String GetCallbackResult()
{
return returnValue;
}
}
和ClientCallback.aspx:
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="ClientCallback.aspx.cs" Inherits="ClientCallback" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML
1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html >
<head id="Head1" runat="server">
<title>Client Callback Example</title>
<script type="text/ecmascript">
function LookUpStock() {
var lb = document.getElementById("<%=ListBox1.ClientID%>");
try {
var product = lb.options[lb.selectedIndex].text;
CallServer(product, "");
}
catch (err) {
alert("Please select a product.");
}
}
function ReceiveServerData(rValue) {
document.getElementById("<%=ResultsSpan.ClientID%>").innerHTML = rValue;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ListBox ID="ListBox1" Runat="server"></asp:ListBox>
<br />
<br />
<input type="button" value="Look Up Stock" onclick="LookUpStock()" />
<br />
<br />
Items in stock: <span id="ResultsSpan" runat="server"></span>
<br />
</div>
</form>
</body>
</html>
【问题讨论】:
标签: c# asp.net .net callback postback