Tom*_*adi 5 c# asp.net asp.net-mvc razor
在我的数据库中,我存储了数据类型为 的字段decimal。我decimal在我的 ASP.NET 应用程序中使用完全相同的 ( ) 数据类型。
这是在我的视图中以显示值。
@Html.TextBoxFor(model => model.Stock, new { id = "Stock", @class = "k-textbox" })
Run Code Online (Sandbox Code Playgroud)
这很直接。我面临的唯一问题是,默认情况下,在我的视图中,数据显示为 4 位小数。
我给你几个例子,说明它的外观和应该如何:
- 1,0000 => 1
- 1,2000 => 1,2
- 1,4300 => 1,43
- 1,8920 => 1,892
- 1,5426 => 1,5426
正如您所看到的,我想切断所有0小数位(仅在视图中显示时)。
请记住:我使用逗号而不是小数点。
编辑:
我的模型
public class Article
{
public decimal? Stock{ get; set; }
}
Run Code Online (Sandbox Code Playgroud)
该方法的G29参数string.Format正是您想要的。
您可以在模型Stock值上使用以下属性。
[DisplayFormat(DataFormatString = "{0:G29}", ApplyFormatInEditMode = true)]
Run Code Online (Sandbox Code Playgroud)
或者您可以使用@Chris 提到的重载。
@Html.TextBoxFor(model => model.Stock, "{0:G29}", new { id = "Stock", @class = "k-textbox" })
Run Code Online (Sandbox Code Playgroud)
{0:G29}你可以这样使用:
@{
string temp = string.Format("{0:G29}", decimal.Parse(Model.Stock.ToString()));
@Html.TextBoxFor(model => temp)
}
Run Code Online (Sandbox Code Playgroud)
或者使用字符串插值:
@{
string temp = $"{decimal.Parse(Model.Stock.ToString()):G29}";
@Html.TextBoxFor(model => temp)
}
Run Code Online (Sandbox Code Playgroud)
编辑:保存后
无法获取值的原因Controller是模型绑定器找不到 name 的属性temp。您可以使用 aTextBox而不是来TextBoxFor解决这个问题,如下所示:
string temp = $"{decimal.Parse(Model.Stock.ToString()):G29}";
@Html.TextBox("Stock" , temp)
Run Code Online (Sandbox Code Playgroud)
或者,如果您仍然想使用,TextBoxFor可以将temp变量重命名为Stock:
string Stock = string.Format("{0:G29}", decimal.Parse(Model.Stock.ToString()));
@Html.TextBoxFor(model => Stock)
Run Code Online (Sandbox Code Playgroud)