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);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
using System.Web.Mvc;
using System.Web.Mvc.Html;
namespace MvcApplication1.Helpers
{
public static class Html5Helper
{
// Using same overload as
public static MvcHtmlString NumberFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes)
{
htmlAttributes["type"] = "number";
return htmlHelper.TextBoxFor(expression, htmlAttributes);
}
public static MvcHtmlString NumberFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression)
{
return htmlHelper.NumberFor(expression, new object());
}
public static MvcHtmlString NumberFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
{
return htmlHelper.NumberFor(expression, htmlAttributes.ToDictionary());
}
public static IDictionary<string, object> ToDictionary(this object src)
{
IEnumerable<PropertyInfo> properties = src.GetType().GetProperties();
return System.Linq
.Enumerable
.Aggregate(properties,
new Dictionary<string, object>(),
(map, pi) =>
{
map[pi.Name] = pi.GetValue(src,new object[] {});
return map;
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment