TextBoxFor十进制 [英] TextBoxFor decimal
问题描述
在我的数据库中,我存储了数据类型为decimal
的字段.我在ASP.NET应用程序中使用的数据类型完全相同(decimal
).
In my database I stored fields with the data type decimal
. I am using exactly the same (decimal
) data type in my ASP.NET application.
这是在我的视图内以便显示值.
This is inside my view in order to display the value.
@Html.TextBoxFor(model => model.Stock, new { id = "Stock", @class = "k-textbox" })
这很简单.我面临的唯一问题是,默认情况下,在我的视图中,数据以4个小数位显示.
This pretty straight forward. The only issue I am facing is that by default in my view the data is displayed with 4 decimal places.
我为您提供一些有关其外观和外观的示例:
I give you a few examples on how it looks and how it should look:
- 1,0000 => 1
- 1,2000 => 1,2
- 1,4300 => 1,43
- 1,8920 => 1,892
- 1,5426 => 1,5426
- 1,0000 => 1
- 1,2000 => 1,2
- 1,4300 => 1,43
- 1,8920 => 1,892
- 1,5426 => 1,5426
如您所见,我想将所有0
都切掉为小数位(仅在视图中显示时).
As you can see I want to cut off all the 0
as decimal places (only when displayed in the view).
请记住:我使用逗号而不是小数点.
Remember: I am using commas instead of decimal points.
我的模特
public class Article
{
public decimal? Stock{ get; set; }
}
推荐答案
您可以像这样使用{0:G29}
:
@{
string temp = string.Format("{0:G29}", decimal.Parse(Model.Stock.ToString()));
@Html.TextBoxFor(model => temp)
}
或使用字符串插值:
@{
string temp = $"{decimal.Parse(Model.Stock.ToString()):G29}";
@Html.TextBoxFor(model => temp)
}
保存后无法在Controller
中获取值的原因是,模型绑定程序找不到名称为temp
的属性.您可以使用TextBox
代替TextBoxFor
来解决此问题,如下所示:
The reason that you can't get the value in your Controller
after you save it is that the model binder can't find a property with name temp
. You can use a TextBox
instead of TextBoxFor
to solve this issue like this:
string temp = $"{decimal.Parse(Model.Stock.ToString()):G29}";
@Html.TextBox("Stock" , temp)
或者,如果您仍然想使用TextBoxFor
,则可以将temp
变量重命名为Stock
:
Or if you still want to use TextBoxFor
you can just rename the temp
variable to Stock
:
string Stock = string.Format("{0:G29}", decimal.Parse(Model.Stock.ToString()));
@Html.TextBoxFor(model => Stock)
这篇关于TextBoxFor十进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!