TextBoxFor decimal

白昼怎懂夜的黑 提交于 2019-12-23 17:03:11

问题


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" })

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

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.

Edit:

My model

public class Article
{
    public decimal? Stock{ get; set; }
}

回答1:


You can use {0:G29} like this:

@{
    string temp = string.Format("{0:G29}", decimal.Parse(Model.Stock.ToString()));
    @Html.TextBoxFor(model => temp)
}

Or with string interpolation:

@{
    string temp = $"{decimal.Parse(Model.Stock.ToString()):G29}";
    @Html.TextBoxFor(model => temp)
}

EDIT: 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)

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)



回答2:


The G29 argument of the string.Format method does exactly what you want.

You can use the the following attribute on your models Stock value.

[DisplayFormat(DataFormatString = "{0:G29}", ApplyFormatInEditMode = true)]

Or you can use the overload which @Chris mentioned.

@Html.TextBoxFor(model => model.Stock, "{0:G29}", new { id = "Stock", @class = "k-textbox" })



回答3:


There is an overload of TextBoxFor that takes a format parameter that it uses to format the text.

This will allow you to format your number in any way you want.



来源:https://stackoverflow.com/questions/45059267/textboxfor-decimal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!