我的模型有一种类型为double的属性。我的一个项的值为0.000028,但当呈现编辑视图时,该值的编辑器显示为2.8e-005。
除了使我的用户感到困惑之外,它还使我的正则表达式验证失败。
[Display(Name = "Neck Dimension")]
[RegularExpression(@"[0-9]*\.?[0-9]+", ErrorMessage = "Neck Dimension must be a Number")]
[Range(0, 9999.99, ErrorMessage = "Value must be between 0 - 9,999.99")]
[Required(ErrorMessage = "The Neck Dimension is required.")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:F20}")]
public double? NeckDimension { get; set; }如何显示这个字段?我得到了这段代码(如下所示),它将呈现出我想要的十进制,但我不知道在哪里实现它。
var dbltest = 0.000028D;
Console.WriteLine(String.Format("{0:F20}", dbltest).TrimEnd('0')); 我在两个地方使用属性NeckDimension,编辑视图和显示视图。这是如何呈现每一个。
@Html.TextBoxFor(model => model.NeckDimension, new { style = "width:75px;" })
@Html.DisplayFor(model => model.NeckHDimension)更新显然DisplayFormat不能与TextBoxFor一起工作。我试图将我的@Html.TextBoxFor更改为一个Html.EditorFor并给它一个类,但是它失败了,只有下面的例外情况。
The model item passed into the dictionary is of type 'System.Double', but this dictionary requires a model item of type 'System.String'这个旧代码仍然有效:
@Html.TextBoxFor(model => model.NeckDimension, new { style = "width:75px;" })此代码提供了例外情况:
@Html.EditorFor(model => model.NeckDimension, new {@class = "formatteddecimal"})看起来我的选择是用javascript修复这个选项,或者用编辑器模板修复它,但是我现在没有时间研究和学习第二个选项。
解决方案:
我为double创建了一个编辑器模板?如下所示。
@model double?
@{
var ti = ViewData.TemplateInfo;
var displayValue = string.Empty;
if (Model.HasValue) {
displayValue = String.Format("{0:F20}", @Model.Value).TrimEnd('0');
}
<input id="@ti.GetFullHtmlFieldId(string.Empty)" name="@ti.GetFullHtmlFieldName(string.Empty)" type="text" value="@displayValue" />
}发布于 2011-10-03 19:00:29
您可以使用[DisplayFormat]属性装饰视图模型上的属性:
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:F20}")]
public double Foo { get; set; }现在,在您的强类型视图中,只需:
@Html.DisplayFor(x => x.Foo)或者如果是为了编辑:
@Html.EditorFor(x => x.Foo)如果您想要将此格式应用于应用程序或每个控制器中的所有双变量,另一种可能是编写一个custom display/editor template。
https://stackoverflow.com/questions/7639377
复制相似问题