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

心已入冬 提交于 2019-12-18 01:31:12

问题


Here is my code in MVC 5:

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

And here is the html code:

<input class="text-box single-line" data-val="true" data-val-number="The field Fix Amount must be a number." data-val-required="The Fix Amount field is required." id="myfloatvalue" name="myfloatvalue" type="text" value="">

Not to

<input class="text-box single-line" data-val="true" data-val-number="The field Fix Amount must be a number." data-val-required="The Fix Amount field is required." id="myfloatvalue" name="myfloatvalue" type="number" min="0" step="0.01" value="0">

What should I do?
Thanks for response!


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/33755560/how-to-force-razor-to-make-editorfor-to-input-number-type-for-float-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!