asp.net-coreasp.net-core-mvc

How to format input number while editing in ASP.NET Core?


This is my code:

<div class="form-group">
    @Html.TextBoxFor(m => m.TotalBudget, new { @class = "form-control"})
    @Html.ValidationMessageFor(m => m.TotalBudget, "", new { @class = "text-danger" })
</div>

It makes an input of number type without formatting.

I want to format input value while editing.

The format that I want is

$###,###,###.##

Examples: $22,123.00, $3,000,000.12

I've tried:

<div class="form-group">
    @Html.TextBoxFor(m => m.TotalBudget, new { @class = "form-control", @format= "${###,###,###,###.##}" }) //@format= "{0:C2}"
    @Html.ValidationMessageFor(m => m.TotalBudget, "", new { @class = "text-danger" })
</div>
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = true)]
[DisplayFormat(DataFormatString = "{$###,###,###,###.##}", ApplyFormatInEditMode = true)]

What did I do wrong?


Solution

  • You Could try JavaScript code to implement your requirement. Below is sample code which will allow you to format the field at editing time with currency.

    Index.cshtml:

    @model WebApplication1.Models.BudgetViewModel
    
    @{
        ViewBag.Title = "Budget Form";
    }
    
    <h2>Enter Budget</h2>
    <div class="form-group">
        @Html.TextBoxFor(m => m.TotalBudget, new { @class = "form-control", @id = "totalBudget" })
        @Html.ValidationMessageFor(m => m.TotalBudget, "", new { @class = "text-danger" })
    </div>
    
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function () {
            $('#totalBudget').on('input', function () {
                // Remove any characters that are not numbers, periods, or commas
                var value = $(this).val().replace(/[^0-9.]/g, '');
    
                // Format the value
                var formattedValue = formatCurrency(value);
    
                // Set the formatted value back to the input field
                $(this).val(formattedValue);
            });
        });
    
        function formatCurrency(value) {
            // Split the value into integer and decimal parts
            var parts = value.split('.');
            var integerPart = parts[0];
            var decimalPart = parts[1] ? '.' + parts[1].slice(0, 2) : '';
    
            // Format the integer part with commas
            var formattedInteger = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    
            // Handle cases when the user enters just the decimal point or a number like "0."
            if (value.endsWith('.')) {
                decimalPart = '.';
            }
    
            // Return the formatted value with a dollar sign
            return '$' + formattedInteger + decimalPart;
        }
    </script>
    

    BudgetViewModel.cs:

    using System.ComponentModel.DataAnnotations;
    
    namespace WebApplication1.Models
    {
        public class BudgetViewModel
        {
            [DataType(DataType.Currency)]
    
            public decimal TotalBudget { get; set; }
    
        }
    }
    

    enter image description here