【发布时间】:2011-07-31 11:35:36
【问题描述】:
我创建了一个自定义控件,其中包含 TextBox 作为子控件(还包含一些其他控件)。在此之后,我将此控件放在 Page 中,并尝试通过 javascript 获取 TextBox 值(即文本)。但我无法直接获取“价值”属性。
自定义控件代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
namespace AjaxServerControlDevelopment
{
public class MyTextBox: CompositeControl
{
/// <summary>
/// TextBox reference variable
/// </summary>
public TextBox objTextBox;
/// <summary>
/// The TextChanged event
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly")]
public event EventHandler TextChanged;
/// <summary>
/// The ButtonClick event
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly")]
public event EventHandler<EventArgs> ButtonClick;
#region Class constructors
/// <summary>
/// Default constructor
/// </summary>
public MyTextBox()
{
////Instantiates the wrapped control
objTextBox = new TextBox();
objTextBox.TextChanged += new EventHandler(objTextBox_TextChanged);
}
#endregion
void objTextBox_TextChanged(object sender, EventArgs e)
{
if (TextChanged != null)
{
TextChanged(this, e);
}
}
#region Property:Text
/// <summary>
/// Gets or sets the Text of TngTextBox
/// Returns:
/// A System.String Object. The default value is System.Null
/// </summary>
public string Text
{
get
{
return objTextBox.Text;
}
set
{
objTextBox.Text = value;
}
}
#endregion
#region ChildControls
/// <summary>
/// Allows us to attach child controls to our composite control
/// </summary>
protected override void CreateChildControls()
{
Controls.Clear();
this.Controls.Add(objTextBox);
base.CreateChildControls();
}
#endregion
}
控件演示页面代码:
<head runat="server">
<title></title>
<script type="text/javascript">
function met1() {
var objTextBox = document.getElementById('<%=MyTextBox1.ClientID %>');
//alert(objTextBox.children[0].value);
alert(objTextBox.value);
}
</script>
<cc1:MyTextBox ID="MyTextBox1" runat="server" />
<br />
<asp:Button ID="Button1" OnClientClick="met1();" runat="server" Text="Button" />
</form>
在 DemoPage 的 ViewSource 中,此控件呈现为 Span Element 内 input Element
所以如果我这样写,我会得到 TextBox 值
document.getElementById('<%=MyTextBox1.ClientID%>').children[0].value
如何像这样公开'value'属性:document.getElementById('').value?
【问题讨论】:
-
我认为提供的 sn-p 不正确或不完整。我没有看到您在页面标记中插入 MyTextBox1 的位置。
-
是 Tengiz,MyTextBox1 控件放置在标记页中。它看起来像这样
标签: asp.net sharepoint custom-controls