首页 > 解决方案 > 使用 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 的情况下正确绑定,或者是否有解决此问题的最佳实践?

标签: jqueryasp.net-core-mvcmodel-bindingusability

解决方案


推荐阅读