TextBoxFor十进制 [英] TextBoxFor decimal

查看:89
本文介绍了TextBoxFor十进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的数据库中,我存储了数据类型为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. 1,0000 => 1
  2. 1,2000 => 1,2
  3. 1,4300 => 1,43
  4. 1,8920 => 1,892
  5. 1,5426 => 1,5426
  1. 1,0000 => 1
  2. 1,2000 => 1,2
  3. 1,4300 => 1,43
  4. 1,8920 => 1,892
  5. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆