Display/Edit a Currency in ASP.NET MVC Core, why so complicated?

后端 未结 2 743
傲寒
傲寒 2021-01-14 03:20

In an ASP.NET Core 2.0 application, I have a Foo class with a lot of classical string or numeric members and also a int? Budget fi

相关标签:
2条回答
  • 2021-01-14 03:24

    My biggest finding was to ensure you are not just rendering the field via your own tag within the .cshtml; rather, ensure you are using the @Html.EditorFor() syntax to render the field:

                    <div class="col-md-10">
                        @Html.EditorFor(model => Model.AmountPaid)
                        <span asp-validation-for="AmountPaid" class="text-danger" />
                    </div>
    

    Once I used this, the validation worked correctly. You can also decorate your field, such as:

        [DataType(DataType.Currency)]
        [Column(TypeName = "decimal(18, 2)")]
        public decimal AmountPaid { get; set; }
    

    https://docs.microsoft.com/en-us/aspnet/core/tutorials/razor-pages/validation?view=aspnetcore-2.2

    0 讨论(0)
  • 2021-01-14 03:32

    I noticed that InputTagHelper has a Format property, which means one can write :

    <input asp-for="Budget" asp-format="{0:C}" class="form-control" />
    

    Finding that though was not easy. It wasn't mentioned in the Input Tag Helper section of the intro. In the end I found it through ASP.NET Core MVC Input Tag Helper Deep Dive

    Now I understand why people say ASP.NET Core's documentation is lacking - the intro goes to great lenghts to explain the various tag helpers in a single article, explains their relation to HTML Helpers, but ommits significant properties like Format. Without direct link to the class's documentation, it takes a bit of digging to find it.

    There are quite a few similar questions in SO with answers that say "you can't format" or propose custom solutions.

    UPDATE

    An issue was opened on July 2017 about POSTing currency values that included a currency symbol. The thread is insteresting as it explains that asp-format only affects display, so the recommended solution is to put the symbol outside the input, possibly using Bootstrap input groups :

    The recommended solution here is to place the currency indicator outside of the editable field (e.g. before or after)

    Perhaps something like this:

    <div class="input-group">
        <input asp-for="Budget" asp-format="{0:#,###.00}" class="form-control" />
        <span class="input-group-addon">€</span>
    </div>
    
    0 讨论(0)
提交回复
热议问题