我有一个用 C# 编写并编译成 dll 的非常简单的用户控件。我使用对象标记将该控件放入 aspx 页面,然后尝试在 javascript 中使用它进行操作。我有其他控件可以正常工作,但出于某种原因,这个控件却不行。这是代码:
using System.Windows.Forms;
namespace FileBrowser {
public partial class theBrowser : UserControl {
public theBrowser() {
InitializeComponent();
MessageBox.Show("TBI");
}
public string theFile = "foobar";
}
}
网页代码如下:
<object id='fileBrowserControl' classid='http:FileBrowser.dll#FileBrowser.theBrowser'>
<span>File control did not initialize.</span>
然后
<script type="text/javascript">
$(function() {
var mfc = $('#fileBrowserControl')[0];
alert(mfc.theFile);
});
当我加载页面时,MessageBox 显示构造函数已触发,但 javascript 警报为组件字符串提供“未定义”。这是精简版,在真实版中,我也不能从javascript调用公共(public)函数。我收到错误消息,“该对象不支持此属性或方法。”
我显然遗漏了一些非常简单的东西,但我没有看到。谢谢你的帮助。 乔恩
最佳答案
是的,ASP.NET 托管代码不会自动连接到客户端脚本,您必须自己连接它。我的建议是:
1) 创建您的 UserControl 作为 Web UserControl
2) 在您的 aspx 页面上注册:http://msdn.microsoft.com/en-us/library/sbz9etab.aspx
3) 在您的用户控件的代码隐藏中,加载后,使用如下内容将您的“theFile”属性值推送到控件的脚本中:
Page.ClientScript.RegisterStartupScript(Page.GetType(),"inject","var theFile='" + this.theFile + "';",true);
4) 然后您可以使用“theFile”变量在 JavaScript 中访问该值
关于c# - ASPX 页面中的用户控件无法使用 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9879047/