Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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