42

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!

4

2 回答 2

77

您是否尝试过将匿名对象包装在htmlAttributes另一个匿名对象中?使用EditorFor/TextBoxFor时,我相信 MVC 5 是影响编辑器输出的 HTML 属性的唯一方法。

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

如果您不使用 MVC-5.1 或更高版本,则需要使用TextBoxFor(). 注意这里没有htmlAttributes使用:

@Html.TextBoxFor(m => m.myfloatvalue, new { type = "number", min = "0", step = "0.01" }) // don't set the value attribute
于 2015-11-17T11:26:47.563 回答
1

您实际上可以将 EditorFor 的默认行为更改为 a float,以便它生成type="number"而不是type="text".

为此,您需要EditorTemplateSingle( not float ) 类型添加自定义,/Views/Shared/EditorTemplates/Single.cshtml如下所示:

@model Single?

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

之所以可行,是因为它float是 C# 的别名System.Single(有关更多详细信息,请参阅Microsoft c# 语言参考)。添加一个EditorTemplate名为 Float.cshtml 将不起作用(我尝试过......)。

我从@Stephen Muecke对我的问题的出色回答中得到了这个想法。他还提到了创建自己的HtmlHelper扩展的想法,这样您就可以编写@Html.FloatFor(...).

同样的方法也可以应用于Decimaland Double,两者都type="text"默认呈现。

于 2018-08-26T11:25:56.463 回答