C# 获取可为null的整数类型验证消息的奇怪行为
有一种奇怪的行为,可以找到发生这种情况的原因。 假设您的模型上有一个可为null的整型属性,并且您希望添加一条验证消息,说明特定属性只接受整数值。 另外,如果您在cshtmml上添加editorfor,那个特定的属性验证消息不会显示,但如果您为它添加文本框,那个么它可以正常工作,有什么想法吗? 请参阅下面的代码 模型 CSHTML不显示错误消息C# 获取可为null的整数类型验证消息的奇怪行为,c#,asp.net-mvc-4,C#,Asp.net Mvc 4,有一种奇怪的行为,可以找到发生这种情况的原因。 假设您的模型上有一个可为null的整型属性,并且您希望添加一条验证消息,说明特定属性只接受整数值。 另外,如果您在cshtmml上添加editorfor,那个特定的属性验证消息不会显示,但如果您为它添加文本框,那个么它可以正常工作,有什么想法吗? 请参阅下面的代码 模型 CSHTML不显示错误消息 <div class="editor-label"> @Html.LabelFor( model => model.Numberof
<div class="editor-label">
@Html.LabelFor( model => model.NumberofProperty )
</div>
<div class="editor-field">
@Html.EditorFor ( model => model.NumberofProperty )
@Html.ValidationMessageFor( model => model.NumberofProperty )
</div>
@LabelFor(model=>model.NumberofProperty)
@Html.EditorFor(model=>model.NumberofProperty)
@Html.ValidationMessageFor(model=>model.NumberofProperty)
显示错误消息的CSHTML
<div class="editor-label">
@Html.LabelFor( model => model.NumberofProperty )
</div>
<div class="editor-field">
@Html.TextBoxFor( model => model.NumberofProperty , new { style= "width:50px"} )
@Html.ValidationMessageFor( model => model.NumberofProperty )
</div>
@LabelFor(model=>model.NumberofProperty)
@Html.TextBoxFor(model=>model.NumberofProperty,新的{style=“width:50px”})
@Html.ValidationMessageFor(model=>model.NumberofProperty)
你知道为什么会有这种行为吗
欢呼声“工作”和“不工作”在没有上下文的情况下是无用的。是什么让他们“不工作”?如果你没有为null int设置编辑器模板,那当然不会像预期的那样工作。嗨,西蒙,你能指定你的意思吗?
EditorFor
只调用TextBox(…)
而不是TextBoxFor
(IIRC)。不带TextBoxFor
。。将不考虑您的模型属性。因此,您需要设置一个EditorTemplate来调用TextBoxFor
,而不是默认的TextBox
。
<div class="editor-label">
@Html.LabelFor( model => model.NumberofProperty )
</div>
<div class="editor-field">
@Html.TextBoxFor( model => model.NumberofProperty , new { style= "width:50px"} )
@Html.ValidationMessageFor( model => model.NumberofProperty )
</div>