Currency Formatting MVC

后端 未结 1 748
野趣味
野趣味 2020-12-03 06:47

I\'m trying to format an Html.EditorFor textbox to have currency formatting, I am trying to base it off of this thread String.Format for currency on a TextBoxFor. However, m

相关标签:
1条回答
  • 2020-12-03 07:06

    You could decorate your GoalAmount view model property with the [DisplayFormat] attribute:

    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:c}")]
    public decimal GoalAmount { get; set; }
    

    and in the view simply:

    @Html.EditorFor(model => model.Project.GoalAmount)
    

    The second argument of the EditorFor helper doesn't do at all what you think it does. It allows you to pass additional ViewData to the editor template, it's not htmlAttributes.

    Another possibility is to write a custom editor template for currency (~/Views/Shared/EditorTemplates/Currency.cshtml):

    @Html.TextBox(
        "", 
        string.Format("{0:c}", ViewData.Model),
        new { @class = "text-box single-line" }
    )
    

    and then:

    @Html.EditorFor(model => model.Project.GoalAmount, "Currency")
    

    or use [UIHint]:

    [UIHint("Currency")]
    public decimal GoalAmount { get; set; }
    

    and then:

    @Html.EditorFor(model => model.Project.GoalAmount)
    
    0 讨论(0)
提交回复
热议问题