我有一个用户控件,其中包含在大型Web应用程序中重复使用的表单项,到目前为止,无效表单提交时的验证摘要由使用用户控件的.aspx处理。 / p>

现在我需要在运行时为每个表单项控件(文本框,列表,验证器等)设置ValidationGroup属性。而不是通过设置我感兴趣的每个控件来手动迭代用户控件中的所有控件,检测该控件是否具有ValidationGroup属性,并以此方式设置它的值。

这样的事情:

For Each ctrl As System.Web.UI.Control In Me.Controls
   ' so now what is the proper way to detect if this control has the ValidationGroup property
Next

vb.net或c#中的代码示例适合我。非常感谢!

有帮助吗?

解决方案

您的UserControl应该公开一个属性,该属性在其自身内部正确设置ValidationGroup属性。

.ASPX中的控制标记:

<ctl:yourcontrol id="whatever" runat="server" YourValidationGroupProp="HappyValidationName" />

控制代码隐藏.ASCX:

 protected override void OnPreRender(EventArgs e)
 {
     someControl.ValidationGroup = YourValidationGroupProp;
     someControl1.ValidationGroup = YourValidationGroupProp;
     someControl2.ValidationGroup = YourValidationGroupProp;
     //......etc
 }    

 public string YourValidationGroupProp{ get; set; }

其他提示

创建一个继承的自定义控件,例如,literal。这个控件将是一个帮手。

您将它插入页面,让它为您完成所有脏工作。 例如输出代码[这将花费大量时间来编写]基于某些逻辑和一旦你完成它。

获取自动代码(这对于每次由另一个控件实际完成的操作会非常重要),删除辅助控件并将新代码硬编码放在任何您想要的位置。

通过这种方式,您可以通过让计算机根据需要计算出您想要的代码来避免所有错误,并获得通过通用方法解决问题所带来的所有硬编码速度。

我只是在寻找同样的事情,它突然袭击了我。 我将这种方法用于其他方面[扫描所有控件&amp;输出一些初始化代码]但我想你也可以使用这种方法轻松完成这个!

我刚刚写了它,我将与你分享

public class ValidationCodeProducerHelper : Literal
{
    // you can set this in the aspx/ascx as a control property
    public string MyValidationGroup { get; set; }

    // get last minute controls
    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);

        // start scanning from page subcontrols
        ControlCollection _collection = Page.Controls;
        Text = GetCode(_collection).Replace("\r\n", "<br/>");
    }

    private string GetCode(Control _control)
    {
        // building helper
        StringBuilder _output = new StringBuilder();

        // the logic of scanning
        if (_control.GetType().GetProperty("ValidationGroup") != null && !string.IsNullOrEmpty(_control.ID))
        {
            // the desired code
            _output.AppendFormat("{0}.{1} = {2};", _control.ID, "ValidationGroup", MyValidationGroup);
            _output.AppendLine();
        }

        // recursive search within children
        _output.Append(GetCode(_control.Controls));

        // outputting
        return _output.ToString();
    }

    private string GetCode(ControlCollection _collection)
    {
        // building helper
        StringBuilder _output = new StringBuilder();
        foreach (Control _control in _collection)
        {
            // get code for each child
            _output.Append(GetCode(_control));
        }
        // outputting
        return _output.ToString();
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top