简体   繁体   English

如何从客户端.ascx使用控件ID并在服务器端ascx.cs(ASP.NET)中使用它

[英]How to use control ID from clientside .ascx and use it in serverside ascx.cs (ASP.NET)

I have a ASP.NET control defined in my .acsx and some code on the server side that checks it in my .cs, creating a new custom validator if the data input is invalid. 我在.acsx中定义了一个ASP.NET控件,并在服务器端通过一些代码在.cs中对其进行了检查,如果数据输入无效,则创建一个新的自定义验证器。

I am trying to make the error message display next to the control, but I am unable to set the ControlToValidate attribute to the ID of the control. 我试图使错误消息显示在控件旁边,但是我无法将ControlToValidate属性设置为ControlToValidateID Visual Studio highlights ContactTelephoneTextBox with the error: Visual Studio突出显示ContactTelephoneTextBox并显示错误:

cannot convert source type 无法转换来源类型

This is the Custom Validator in the .cs 这是.cs中的自定义验证程序

Page.Validators.Add(new CustomValidator()
{
    Display = ValidatorDisplay.Dynamic,
    ControlToValidate = ContactTelephoneTextBox, 
    ID = "phoneInvalid",
    IsValid = false,
    ErrorMessage = "Please enter a valid phone number.", 
    field",
});

In my .ascx 在我的.ascx中

<div id="ContactTelephone">
    <asp:Label ID="ContactTelephoneLabel" AssociatedControlID="ContactTelephoneTextBox"
        CssClass="required formFont2015 formLabel2015" runat="server">Contact number</asp:Label>
    <asp:TextBox ID="ContactTelephoneTextBox" CssClass="boxStyle2015" runat="server"></asp:TextBox>
</div>

ControlToValidate expects a string not a control, so this should work: ControlToValidate需要一个字符串而不是一个控件,所以这应该可以工作:

Page.Validators.Add(new CustomValidator()
{
    Display = ValidatorDisplay.Dynamic,
    ControlToValidate = ContactTelephoneTextBox.ClientID, 
    ID = "phoneInvalid",
    IsValid = false,
    ErrorMessage = "Please enter a valid phone number.", 
    field",
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM