C# 查看时显示货币的问题

C# 查看时显示货币的问题,c#,asp.net-mvc-5,decimal,C#,Asp.net Mvc 5,Decimal,我有以下几点 public decimal? Price {get;set;} 当我在视图的文本框(下面的文本框)中输入3000.00时 价格 @Html.ValidationMessageFor(m=>m.Price) £ @text.TextBoxFor(m=>m.Price,新的{@class=“form control”,type=“text”,id=“txtPrice”,onkeypress=“return isNumberKey(event)”}) 十进制格式 看起来是这样的

我有以下几点

public decimal? Price {get;set;}
当我在视图的文本框(下面的文本框)中输入3000.00时


价格
@Html.ValidationMessageFor(m=>m.Price)
£
@text.TextBoxFor(m=>m.Price,新的{@class=“form control”,type=“text”,id=“txtPrice”,onkeypress=“return isNumberKey(event)”})
十进制格式

看起来是这样的

它在数据库中保存为3000.00,这是预期值,但当我返回视图进行编辑时,文本框中的值为3000.0000

我在这里尝试了一些解决方案


我认为我的问题是视图上的字段是decimal类型而不是字符串,因此我不确定如何格式化此十进制以删除尾随的零,因此它看起来像上面的图片,您需要使用接受格式字符串的oveload of
TextBoxFor

@Html.TextBoxFor(m => m.Price, "{0:0.00}", new { @class = "form-control", type = "text", id = "txtPrice", onkeypress = "return isNumberKey(event)"})
旁注:

  • 删除
    type=“text”
    。html帮助程序已经为您添加了此内容(添加 您是否有理由不使用默认的
    id
    助手,它将是
    id=“Price”
    ?)
  • 而不是使用污染你的标记 使用行为-例如,
    $(“#txtPrice”)。按键(…

  • 使用重载来接受格式字符串
    @Html.TextBoxFor(m=>m.Price,“{0:0.00}”,new{……})
    正确我应该使用默认Id,我只是习惯于写Id等,所以我需要养成习惯,让助手分配Id,我还将更改按键的工作方式。再次感谢
    @Html.TextBoxFor(m => m.Price, "{0:0.00}", new { @class = "form-control", type = "text", id = "txtPrice", onkeypress = "return isNumberKey(event)"})