Skip to content

Instantly share code, notes, and snippets.

Created January 5, 2012 16:58
Show Gist options
  • Save anonymous/1566126 to your computer and use it in GitHub Desktop.
Save anonymous/1566126 to your computer and use it in GitHub Desktop.
NumberFor extension for HtmlHelper
using System;
using System.Linq.Expressions;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Text.RegularExpressions;
namespace Website.Extensions
{
public static class HtmlExtensions
{
public static MvcHtmlString NumberFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
{
return htmlHelper.NumberFor(expression, null);
}
public static MvcHtmlString NumberFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
{
Regex regex = new Regex(@"type\s*=\s*""text""", RegexOptions.IgnoreCase);
string html = string.Empty;
if (htmlAttributes == null)
{
html = InputExtensions.TextBoxFor(htmlHelper, expression).ToHtmlString();
}
else
{
html = InputExtensions.TextBoxFor(htmlHelper, expression, htmlAttributes).ToHtmlString();
}
if(regex.IsMatch(html))
{
html = regex.Replace(html, "type=\"number\"");
}
return MvcHtmlString.Create(html);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment