我正在使用 ASP.NET 4.0 WebForms 并使用控件。但是我想添加 3 个文本框、电子邮件、密码和出生日期。电子邮件和密码是标准的用户名和密码,但如果我有第三个出生日期文本框(在登录按钮上方但在电子邮件和密码下方),在我后面的代码中,此控件的 ID 无法识别,因为它介于标签的范围。
有没有办法用这个控件添加更多控件,然后分别对它们进行身份验证?
我正在使用 ASP.NET 4.0 WebForms 并使用控件。但是我想添加 3 个文本框、电子邮件、密码和出生日期。电子邮件和密码是标准的用户名和密码,但如果我有第三个出生日期文本框(在登录按钮上方但在电子邮件和密码下方),在我后面的代码中,此控件的 ID 无法识别,因为它介于标签的范围。
有没有办法用这个控件添加更多控件,然后分别对它们进行身份验证?
从 Visual Studio 设计视图中,您可以将 asp:LoginControl 转换为模板。然后,这会公开控件中的所有 html。然后,您可以在其中添加您想要的任何内容。
<asp:Login ID="Login1"
runat="server">
<LayoutTemplate>
<table cellpadding="1" cellspacing="0" style="border-collapse:collapse;">
<tr>
<td>
<table cellpadding="0">
<tr>
<td align="center" colspan="2">
Log In</td>
</tr>
<tr>
<td align="right">
<asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName">User Name:</asp:Label>
</td>
<td>
<asp:TextBox ID="UserName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="UserNameRequired" runat="server"
ControlToValidate="UserName" ErrorMessage="User Name is required."
ToolTip="User Name is required." ValidationGroup="Login1">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="right">
<asp:Label ID="PasswordLabel" runat="server" AssociatedControlID="Password">Password:</asp:Label>
</td>
<td>
<asp:TextBox ID="Password" runat="server" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="PasswordRequired" runat="server"
ControlToValidate="Password" ErrorMessage="Password is required."
ToolTip="Password is required." ValidationGroup="Login1">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td colspan="2">
<asp:CheckBox ID="RememberMe" runat="server" Text="Remember me next time." />
</td>
</tr>
<tr>
<td align="center" colspan="2" style="color:Red;">
<asp:Literal ID="FailureText" runat="server" EnableViewState="False"></asp:Literal>
</td>
</tr>
<tr>
<td align="right" colspan="2">
<asp:Button ID="LoginButton" runat="server" CommandName="Login" Text="Log In"
ValidationGroup="Login1" />
</td>
</tr>
</table>
</td>
</tr>
</table>
</LayoutTemplate>
</asp:Login>
在您后面的代码中,您将需要使用Login1.FindControl("")您想要访问的任何其他控件。
因此,对于一个新的 asp:textbox,您可以将其设置为:
<asp:TextBox id="TextBox1" runat="server" />
在后面的代码中:
TextBox TextBox1 = (TextBox)Login1.FindControl("TextBox1");
您还可以通过编程向 ASP 登录控件添加一个或多个附加控件!例如,您可以像这样添加一个新的文本框:
// Override the OnInit() method.
override protected void OnInit(EventArgs e)
{
// Dynamically create controls
var newTextBoxControl = new TextBox();
newTextBoxControl.Text = "dfsdf";
newTextBoxControl.ID = "PinCode";
newTextBoxControl.MaxLength = 5;
newTextBoxControl.CssClass="form-control";
var targetControl=FindControlRecursive(Login1, "Login1_LoginButton");
targetControl.Parent.Controls.AddAt(0,txt);
}
private Control FindControlRecursive(Control control, string controlId)
{
if (control.ClientID == controlId) return control;
Control result = null;
foreach (Control childControl in control.Controls)
{
result = FindControlRecursive(childControl, controlId);
if (result != null)
break;
}
return result;
}