mvc.net验证支持ValidationGroup的概念
问题描述:
从asp.net背景来看,我非常赞赏在向页面添加验证时'validationGroup'的概念。我一直在mvc.net中寻找相应的概念,并没有太多的运气。mvc.net验证支持ValidationGroup的概念
这个概念是否可用于mvc.net?如果没有,我有什么替代方案?
答
不幸的是,它没有像这样的东西。
我在一段时间的博客上写了一个解决方法。
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,
查尔斯
答
查尔斯的方法是我能找到的唯一方法实际为我的目的工作! (在一个MVC页面上有两种形式 - >没有在partials和partial属性的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>");
}
}
}
答
扩展查尔诺的答案,并包括HtmlAttributes和其他ValidationSummary属性:
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);
}
一种替代方法是在ASP.NET中无法实现的技术。即,多个