jquery - 使用 DisplayFormat 属性后如何处理模型绑定
问题描述
我正在开发使用大量货币价值和百分比的财务软件。在不考虑可用性的情况下,如果您创建一个默认 TextBox 并将其绑定到一个 decimal 0.00M
,它在用户看来是0.00
. 他们应该将 6% 输入为 6.00 还是 0.06,这是不明确的。您还会遇到 0.065 显示为 0.06 的问题,这会使用户觉得该值不正确。
为了阐明数字的意图,我使用如下显示属性:
[Display(Name = "State Tax Rate")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:P2}")]
public decimal StateRate { get; set; }
[Display(Name = "Combined Tax Rate")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:P2}")]
public decimal CombinedRate { get; set; }
[Display(Name = "County Tax Rate")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:P2}")]
public decimal CountyRate { get; set; }
现在 6.5% 显示为 6.50%,从可用性的角度来看这更好,但是当您将表单发布到 ASP.Net Core MVC 控制器时,这些值不会绑定。简单地去掉百分号会导致它以 650% 绑定。我正在采取的方法是在发布之前使用 JQuery 来清理数据:
// deal with percentages:
// 6.5% does not bind, but is displayed to the user.
// 6.5 binds incorrectly (650%)
// .065 is desired format
$(function () {
$('#my-form').on('submit', function (e) {
e.preventDefault(); // avoid default post routine
// change "6.50%" to 6.5
var stateRate = parseFloat($('#StateRate').val().replace('%', ''));
var combinedRate = parseFloat($('#EstCombinedRate').val().replace('%', ''));
var countyRate = parseFloat($('#EstCountyRate').val().replace('%', ''));
// change 6.5 to .065 - leave 0.065 alone.
if (stateRate > 1) {
stateRate = stateRate / 100.0;
}
if (combinedRate > 1) {
combinedRate = combinedRate / 100.0;
}
if (countyRate > 1) {
countyRate = countyRate / 100.0;
}
// put the cleaned up values back into the form fields
$('#StateRate').val(stateRate);
$('#CombinedRate').val(combinedRate);
$('#CountyRate').val(countyRate);
// make ajax request
$.post(
'/MyController/EditTaxRates'
$(this).serialize(),
function (data, status, jqXHR) {
$.notify('Data saved successfully!', { position: "top center" });
}
).fail(function () {
$.notify('Error saving data.', { position: "top center" });
});
});
});
这在大多数情况下都可以正常工作,但是我需要在很多地方实现它,这会添加很多代码来解决一个看似基本且简单的问题。此外,对于县级税率(例如 0.5%),它在使用此代码时绑定为 50%。是否有任何内置技巧(例如属性或 Razor 魔术)会导致数据在不使用 javascript 的情况下正确绑定,或者是否有解决此问题的最佳实践?
解决方案
推荐阅读
- variables - Ansible:vars_prompt 的问题,错误:变量未定义
- shell - 用于查找(和删除)来自 rar 的视频文件的 Shell 脚本
- javascript - MediaRecorder 类在 Electron APP 中不可用
- react-native - 深度链接 - 如果应用程序关闭则不起作用
- c# - 我需要使用 regex (Address) C# 替换一些单词
- java - 如何读取 SOAP 请求正文元素而不在 Java SpringWS 中的 xsd 或 wsdl 中声明它?
- opencv - 如何在 google colab 中使用 opencv 显示 mp4
- go - Kafka:Sarama、幂等性和 transactional.id
- r - 我可以在 ggplot 条形图中选择要着色的特定行吗?
- google-analytics - Google Analytics(分析)目标转化限制