Skip to content

Instantly share code, notes, and snippets.

@amirci
Forked from anonymous/C# NumberFor
Created January 7, 2012 16:29
Show Gist options
  • Save amirci/1575196 to your computer and use it in GitHub Desktop.
Save amirci/1575196 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);
}
}
}
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