这是我的代码:
<div class="form-group">
@Html.TextBoxFor(m => m.TotalBudget, new { @class = "form-control"})
@Html.ValidationMessageFor(m => m.TotalBudget, "", new { @class = "text-danger" })
</div>
无需格式化即可输入数字类型。
我想在编辑时格式化输入值。
我想要的格式是
$###,###,###.##
示例:
$22,123.00
、$3,000,000.12
我已经尝试过:
<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)]
我做错了什么?
您可以尝试使用 JavaScript 代码来实现您的需求。下面是示例代码,它允许您在编辑时使用货币格式化字段。
索引.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; }
}
}