Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force Razor to make Editorfor to input number type for float variable?

People also ask

How do I add an EditorFor style?

EditorFor does not allow for styling as there are no parameters for additional attributes. The reason for this is because the EditorFor doesn't always generate a single element as it can be overridden. To style a specific type of element you need to use the specific editor you want to use.

What is EditorFor?

EditorFor<TModel,TValue>(HtmlHelper<TModel>, Expression<Func<TModel,TValue>>, String, String, Object) Returns an HTML input element for each property in the object that is represented by the expression, using the specified template, HTML field name, and additional view data.

What is the difference between TextBoxFor and EditorFor in MVC?

TextBoxFor: It will render like text input html element corresponding to specified expression. In simple word it will always render like an input textbox irrespective datatype of the property which is getting bind with the control. EditorFor: This control is bit smart.


Have you tried wrapping your anonymous object in the htmlAttributes of another anonymous object? When using EditorFor/TextBoxFor, I believe in MVC 5 that's the only way of affecting the HTML attributes output by the editor.

@Html.EditorFor(model => model.myfloatvalue, new { htmlAttributes = new { @type = "number", @min = "0", @step = "0.01", @value = "0" }})

If you not using MVC-5.1 or higher, then you will need to use TextBoxFor(). Note no htmlAttributes used here:

@Html.TextBoxFor(m => m.myfloatvalue, new { type = "number", min = "0", step = "0.01" }) // don't set the value attribute

You can actually change the default behaviour for the EditorFor for a float so that it produces type="number" instead of type="text".

To do that you need to add a custom EditorTemplate for the Single (not float) type to /Views/Shared/EditorTemplates/Single.cshtml as follows:

@model Single?

@{
    var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(ViewData["htmlAttributes"]);
    if (!attributes.ContainsKey("type")) { attributes.Add("type", "number"); }
}
@Html.TextBoxFor(m => m, attributes)

The reason this works is that float is a C# alias for System.Single (see the Microsoft c# Language Reference for more details on that). Adding an EditorTemplate called Float.cshtml will not work (I tried...).

I got the idea for this from @Stephen Muecke's excellent answer to my question here. He also mentions the idea of creating your own HtmlHelper extension so you could then write @Html.FloatFor(...).

This same approach can also be applied to Decimal and Double, both of which also render type="text" by default.