aspx 页面中多个下拉列表的必填字段验证器
我有一个 aspx 页面,其中有 18 个(是的 18 个)下拉列表和 18 个文本框。需要选择每个下拉列表并填充每个文本框。在这 36 个控件上拖放所需的字段验证器并维护它们是一项痛苦的任务,而且似乎不是一个合乎逻辑的选项,因为我需要的只是让用户从下拉列表中选择一个值。
无论如何,我是否可以循环遍历所有这些下拉控件和文本框控件,检查它们是否为空并相应地向用户显示警告?客户端验证解决方案或服务器端验证解决方案适合我。
I have an aspx page which has 18 (yes 18) dropdown lists and 18 text boxes. Each dropdown needs to be selected and each textbox needs to be filled. Dragging and dropping required field validators on these 36 controls and maintaining them is a painful task and does not seem to be the logical option as all I need is for the user to select a value from the dropdown.
Is there anyway I can loop through all these dropdown controls and textbox controls, check if they are empty and display warnings to users accordingly? Client-side validation solution or server side validation solution is fine with me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 CustomValidator 并具有客户端脚本函数,确保每个文本框/下拉列表都有一个值。
Use a CustomValidator and have a client script function that makes sure every text box/drop down has a value.
一项建议是循环遍历所有控件 在页面中,使用递归函数动态绑定RequiredFieldValidator 添加到找到的控件。您可以调整我的代码以满足您的需求。
不过,此代码有一些缺点:
.aspx
.cs
One suggestion is to loop through all the controls on the page, use recursive function to dynamically bind RequiredFieldValidator to the found controls. You can tweak my code to suit your needs.
This code has some drawbacks though:
.aspx
.cs
如果您动态生成文本框和下拉列表,您可能还想动态生成验证控件,但如果所有下拉列表和文本框都是静态的,您可以使用以下内容:
使用 CustomValidator Web 控件,编写客户端 javascript检查下拉列表和文本框的所有属性并使用该函数配置 Web 控件的 ClientValidationFunction 并设置 EnableClientScript=true 的方法。另外,b/c 并非所有用户都启用了 javascript,而且为了确保这是最佳实践,始终还创建一个服务器端验证函数并在提交操作上调用 Page.IsValid()。
.aspx 示例代码
c# 代码隐藏示例代码
If you are dynamically generating the textboxes and dropdownlists, you would probably want to dynamically generate the validation controls as well, but if all the drop down lists and textboxes are static you can use the following:
Use a CustomValidator Web Control, write client side javascript method that checks all the properties of the drop down lists and the textboxes and configure the web control's ClientValidationFunction with the function and set EnableClientScript=true. Also, b/c not all users have javascript enabled, plus to be sure as it is best practice, always also create a server side validation function as well and call Page.IsValid() on the submit action.
.aspx Sample Code
c# codebehind sample code