I currently have a situation where I have two separate actions that rendered the same view and then on this view it has two individual forms which post to the two aforementioned controller actions.
Each of the forms have their own separate ValidationSummary() calls to display their validation errors. But when I posted to either one of these actions and the validation failed, I quickly realised a short coming of the built in ValidationSummary() helper method… you see, it doesn’t have a clue about which form has the errors!
Confused yet? Oddly enough, so am I.
A screen shot should clear things up:

And the fail:

Making sense now? Good...
Anyway, I came up with an easy enough work around so I thought I would share it.
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;
}
}
}
I'm (basically) calling it like so:
<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>
And that's it. Enjoy.
Technorati Tags:
asp.net-mvc