Razor HTML Helpers are convenient methods that return HTML strings representing different types of content. In this tutorial I’ll explain how to extend the Razor validation message helper so it integrates with Foundation’s Abide Validation library.
Open a ASPASP Dot Net MVC project. Right-click the solution name and selectAdd a new project
and select Class Library
. Create a new folder named Extensions
and, within this folder, add a static class named HtmlFormExtensions
. Inside this class we’ll add a method named FoundationValidationMessageFor
that outputs a validation message in the format expected by Abide.
using System;
using System.Linq.Expressions;
using System.Web.Mvc;
using System.Web.Mvc.Html;
namespace YourClassLibrary.Extensions
{
public static class HtmlFormExtensions
{
public static MvcHtmlString FoundationValidationMessageFor<TModel, TProperty>(
this HtmlHelper<TModel> helper,
Expression<Func<TModel, TProperty>> expression)
{
// Check if an error exists, otherwise return empty.
if (helper.ValidationMessageFor(expression) != null)
{
TagBuilder small = new TagBuilder("small");
small.AddCssClass("error-message");
small.InnerHtml = helper.ValidationMessageFor(expression).ToHtmlString();
return MvcHtmlString.Create(small.ToString());
}
return MvcHtmlString.Create(String.Empty);
}
}
}
To use this extension method in a ASPASP Dot Net MVC project, you need to add a reference to the class library as well as add the extension class namespace to the Web.config file in the Views folder.
Under the MVC project, right-click on References
and select Add a reference
. In the window that appears, under Solution
, select the name of the class library containing your extension method.
<configuration>
<system.web.webPages.razor>
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="YourClassLibrary.Extensions" />
</namespaces>
</pages>
</system.web.webPages.razor>
</configuration>
You’re now ready to use the extension method. See an example below for its usage. Note that you still need to add the Foundation Abide CSS and JavaScript to your page for the integration to work properly.
@Html.LabelFor(x => x.EmailAddress)<span class="required">\*</span>
@Html.TextBoxFor(x => x.EmailAddress, new Dictionary<string, Object> { { "required", "" }, { "pattern", "email" } })
<small class="error">A valid email address is required.</small>
@Html.FoundationValidationMessageFor(x => x.EmailAddress)