我有一些用 C# 为我的 Web 应用程序构建的自定义控件。我还使用 Visual Studio 2013。
控制:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="YearsTextBox.ascx.cs" Inherits="MutualExpert.Controls.YearsTextBox" %>
<div class="input-group">
<asp:TextBox ID="tb" runat="server" CssClass="form-control text-right" />
<div class="input-group-addon">Years</div>
</div>
从 ASPX 页面调用它,我想在以下位置使用它:
<cc:YearsTextBox runat="server" ID="tbDamageLife" />
我希望控件在页面上呈现为“tbDamageLife”
我尝试过的:
如果我指定 ClientIDMode="Static",则会得到 ID="tb":
<div class="input-group">
<input name="ctl00$cpMain$tbDamageLife$tb" id="tb" class="form-control text-right" type="text">
<div class="input-group-addon">Years</div>
</div>
如果我不这样做,我会得到 ID="ctl00_cpMain_tbDamageLife_tb":
<div class="input-group">
<input name="ctl00$cpMain$tbDamageLife$tb" id="ctl00_cpMain_tbDamageLife_tb" class="form-control text-right" type="text">
<div class="input-group-addon">Years</div>
</div>
我只是想让它渲染 tbDamageLife,即我给它的 ID。
这是一个棘手的问题,我需要这些是静态的,以便 JS 访问它进行计算。有必要。如果可以的话我会解决这个问题,但我就是做不到。
最佳答案
UserControl 本身在 html 中没有 ID,只有在代码中。因此,针对您的情况,最好的解决方案是将 UserControl 内容包装在面板中,并为其指定 ID tbDamageLife
。 。这将成为 <div>
与类(class)input-group
.
<asp:Panel ID="tbDamageLife" runat="server" CssClass="input-group">
<asp:TextBox ID="tb" runat="server" CssClass="form-control text-right" />
<div class="input-group-addon">Years</div>
</asp:Panel>
在父页面上
<cc:YearsTextBox runat="server" ID="tbDamageLife" ClientIDMode="Static" />
将呈现为
<div id="tbDamageLife" class="input-group">
<input name="ctl00$cpMain$tbDamageLife$tb" type="text" id="tb" class="form-control text-right" />
<div class="input-group-addon">Years</div>
</div>
但是,如果您要添加多个控件,则会有重复的 ID。
或者,如果您不需要面板控件的功能,您可以简单地执行以下操作。
<div id="tbDamageLife" class="input-group">
<asp:TextBox ID="tb" runat="server" CssClass="form-control text-right" />
<div class="input-group-addon">Years</div>
</div>
关于javascript - 创建一个自定义用户控件,该控件使用我提供的 ID 并遵循 ClientIDMode ="Static",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51792327/