I found my self wanting the number spinner you get when using <input type='number' />
from an HtmlHelper, and ended up solving it my self.
In a similar fashion to RPAlbert's Html.EmailFor answer above, I started off using the normal Html.TextBoxFor, but then I used LinqToXml to modify the HTML rather than just using a string replace.
The advantage of starting with the Html.TextBoxFor is that you can use of all the client side validation stuff that MVC does for you. In this case I am using the values from the data-val-range
attributes to set the min/max attributes needed to constrain the spinner.
public static HtmlString SpinnerFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object htmlAttributes)
{
XDocument _xml = XDocument.Parse(html.TextBoxFor(expression, htmlAttributes).ToString());
XElement _element = _xml.Element("input");
if (_element != null)
{
_element.SetAttributeValue("type", "number");
if (_element.Attribute("data-val-range-max") != null)
_element.SetAttributeValue("max", _element.Attribute("data-val-range-max").Value);
if (_element.Attribute("data-val-range-min") != null)
_element.SetAttributeValue("min", _element.Attribute("data-val-range-min").Value);
}
return new HtmlString(_xml.ToString());
}
You would then use it as you would any other HtmlHelper in your views:
@Html.SpinnerFor(model => model.SomeNumber, new { htmlAttribute1 = "SomeValue" })
This was my implementation of it anyway, from you question I can see that you wanted:
@Html.NumericInputFor(model => model.Foo, min:0, max:100)
It would be very simple to tweak my method to do this as follows:
public static HtmlString NumericInputFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, int min, int max)
{
XDocument _xml = XDocument.Parse(html.TextBoxFor(expression, htmlAttributes).ToString());
XElement _element = _xml.Element("input");
if (_element != null)
{
_element.SetAttributeValue("type", "number");
_element.SetAttributeValue("min", min);
_element.SetAttributeValue("max", max);
}
return new HtmlString(_xml.ToString());
}
Basically all I have done is to rename it and provide min/max as arguments rather than getting them from DataAnnotation attributes.
I hope that helps!