代码之家  ›  专栏  ›  技术社区  ›  yamspog

MVC.NET验证是否支持validationgroup的概念?

  •  4
  • yamspog  · 技术社区  · 15 年前

    从ASP.NET的背景来看,在向页面添加验证时,我非常欣赏“validationgroup”的概念。我一直在mvc.net中寻找一个相应的概念,但运气并不好。

    这个概念在MVC.NET中可用吗?如果没有,我还有什么选择?

    3 回复  |  直到 12 年前
        1
  •  6
  •   Charlino    15 年前

    不幸的是,没有,它没有像那样的东西。

    我在博客上写了一段时间前的工作。

    ASP.NET MVC - Validation Summary with 2 Forms & 1 View

    博客文章的jist:

    namespace System.Web.Mvc
    {
        public static class HtmlExtensions
        {
            public static string ActionValidationSummary(this HtmlHelper html, string action)
            {
                string currentAction = html.ViewContext.RouteData.Values["action"].ToString();
    
                if (currentAction.ToLower() == action.ToLower())
                    return html.ValidationSummary();
    
                return string.Empty;
            }
        }
    }
    

    <h2>Register</h2>
    
    <%= Html.ActionValidationSummary("Register") %>
    
    <form method="post" id="register-form" action="<%= Html.AttributeEncode(Url.Action("Register")) %>">
    
        ... blah ...
    
    </form>
    
    
    <h2>User Login</h2>
    
    <%= Html.ActionValidationSummary("LogIn") %>
    
    <form method="post" id="login-form" action="<%= Html.AttributeEncode(Url.Action("LogIn")) %>">
    
        ... blah ...
    
    </form>
    

    HTHs
    查尔斯

        2
  •  2
  •   planetClaire    12 年前

    扩展charlino的答案,包括htmlattributes和其他验证摘要属性:

            public static MvcHtmlString ActionValidationSummary(this HtmlHelper html, string action, bool excludePropertyErrors, string message, object htmlAttributes = null)
        {
            var currentAction = html.ViewContext.RouteData.Values["action"].ToString();
    
            if (currentAction.ToLower() == action.ToLower())
            {
                return html.ValidationSummary(excludePropertyErrors, message, htmlAttributes);
            }
    
            return new MvcHtmlString(string.Empty);
        }
    
        3
  •  1
  •   James S    13 年前

    查尔斯的方法是唯一的方法,我可以发现,实际上是为我的目的工作! (即,一个MVC页面上有两个表单->,不在partials内执行表单,而为partials加载Ajax。这对我没有好处,因为我想返回不同的结果集,这些结果集将在表单DIV之外呈现,具体取决于提交的表单)

    不过,我建议对HTML扩展进行轻微修改,因为您仍然希望为不匹配的验证摘要呈现验证摘要,以便客户端验证工作:

    namespace System.Web.Mvc
    {
        public static class HtmlExtensions
        {
            public static MvcHtmlString ActionValidationSummary(this HtmlHelper html, string action)
            {
                string currentAction = html.ViewContext.RouteData.Values["action"].ToString();
    
                if (currentAction.ToLower() == action.ToLower())
                    return html.ValidationSummary();
    
                return new MvcHtmlString("<div class=\"validation-summary-valid\" data-valmsg-summary=\"true\"><ul><li style=\"display:none\"></li></ul></div>");
            }
        }
    }