Better Numeric Range Input with ASP.NET MVC, HTML5 and JQuery

The Sin

I recently wrote this horrible code to generate a drop down box to select any number from 1 to 12.

Ouch! It was only a test harness but after an hour I still got sick of looking at it. It’s a sin that needs to be atoned for.

The Penance

For my penance I’ve said 5 Hail Marys and identified three better ways to generate numeric range dropdowns.

Using Enumerable.Range

If I want to stick with MVC and C# then there is a static method on Enumerable that will generate sequences of numbers i.e.

Will output 1 through to 12 as a list of ints. Leveraging this, my grotesque piece of Razor becomes

Which renders out as a normal dropdown as before

Enumerable.Range

Much better.

Using HTML5

Of course we don’t even need to get into C#. If we’ve got the luxury of a modern browser we can just use HTML5 to give us a slider control.

Which renders as

HTML5

Better again.

Using JQuery

If you don’t have the luxury of a modern browser then you can fall back to JQuery UI which has a larger range of supported browsers. The code isn’t that much more but of course you need to reference JQuery and JQuery UI libraries. It’s another slider type control and the implementation is

Which looks like

JQuery UI

So much nicer.

The Atonement

To atone for my sin I swapped out the horrible code for the Enumerable.Range implementation. I think that’s my preference really. I don’t really want to include a whole bunch of scripts and css to get a decent control (JQuery) and I don’t want to limit myself to the latest and greatest browsers (HTML5). Beside I think Enumerable.Range is little known but pretty smart and let’s face it – who doesn’t want to be little known but pretty smart.

Useful links

https://www.dotnetperls.com/enumerable-range
Nice article on Enumerable.Range

http://www.htmlgoodies.com/html5/tutorials/whats-new-in-html5-forms-handling-numeric-inputs-using-the-number-and-range-input-types.html
More on the HTML slider control

https://jqueryui.com/slider/
Official documentation for the JQueryUI slider control

https://github.com/timbrownls20/Demo/blob/master/ASP.NET%20Core/Demo/Demo/Views/Demo/NumericDropdown.cshtml
As always there are code sample of all implementations on my git hub site.

 

Leave a Reply

Your email address will not be published. Required fields are marked *