C# GUI控制验证模式

C# GUI控制验证模式,c#,asp.net,asp.net-mvc,design-patterns,frontend,C#,Asp.net,Asp.net Mvc,Design Patterns,Frontend,我正在努力寻找一种合适或优雅的方式来处理服务器端代码中的验证。 目前我正在使用asp.net网站,但是我希望有一个同样适用于MVC的模式 我发布的示例/psuedo代码纯粹是为了描述问题,实际代码差异很大,非常复杂: 标记代码如下所示: <asp:CheckBoxList ID="CheckBoxList1" runat="server"> <asp:ListItem>Item1</asp:ListItem> <a

我正在努力寻找一种合适或优雅的方式来处理服务器端代码中的验证。 目前我正在使用asp.net网站,但是我希望有一个同样适用于MVC的模式

我发布的示例/psuedo代码纯粹是为了描述问题,实际代码差异很大,非常复杂:

标记代码如下所示:

    <asp:CheckBoxList ID="CheckBoxList1" runat="server">
        <asp:ListItem>Item1</asp:ListItem>
        <asp:ListItem>Item2</asp:ListItem>
        <asp:ListItem>Item3</asp:ListItem>
    </asp:CheckBoxList>
    <asp:CheckBoxList ID="CheckBoxList2" runat="server">
        <asp:ListItem>Item4</asp:ListItem>
        <asp:ListItem>Item5</asp:ListItem>
        <asp:ListItem>Item6</asp:ListItem>
    </asp:CheckBoxList>
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
    <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" />
protected void Button1_Click(object sender, EventArgs e)
{
    if (ValidatePage()) {
        //call business layer and do some operation.
    }
}

bool ValidatePage()
{
    int visibility = GetVisibility();
    switch (visibility)
    {
        case 0: //TextBox1.Text can not be empty
        //in case it is found to be empty then return false and print the message in web page
        case 1: //TextBox1.Text can not be empty
        //in case it is found to be empty then return false and print the message in web page
        case 2: // both of textbox1 and textbox2 should not be empty
        //in case they are found to be empty then return false and print the message in web page

    }
    //return true or false as per the above validations
}
int GetVisibility()
{
    //if page is redirected from page1 then return 1
    //if page is redirected from page2 then return 2
    //if page is directly open from homepage then return 0
    return 0;
}

  • 问题是,随着复选框的增多,验证变得越来越复杂 选中(换句话说,查看更多上下文)

  • 我正在考虑 作为一个上帝的方法,将提供所有的验证,无论什么 页面中的哪个按钮正在调用它(我对任何 对该方法的建议/批评)

  • 页面是从头开始创建的,新功能/控件/验证是 经常添加
  • 注意:


    我知道Requiredfield验证器,由于一些复杂性,我在这里避免使用它。

    我将创建一个包含对相关控件引用的类,以及一个
    Validate()
    方法(可以在子类中实现或作为lambda传入)。然后我将实例保存在一个集合中,我将迭代调用每个
    Validate()