【问题标题】:Cost must be multiple by 5成本必须是 5 的倍数
【发布时间】:2022-02-10 07:44:27
【问题描述】:

我正在使用基本的CRUD operation 处理小型应用程序,并且我有Product Model。 在这个模型中,我有类似的东西

public class Product  
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public int amountAvailable { get; set; }
        public double cost { get; set; }

        [ForeignKey(nameof(User))]
        public int UserId { get; set; }
        public User Users { get; set; }
        
    }

现在,我需要一些捷径或一些技巧来计算成本(产品成本),但它应该是 5 的倍数,这意味着价格可以是 5、10、15、20、25、30。 .. ETC。 有什么我可以强迫用户这样定价的吗? 我尝试使用[DataAnnotation]Range,但我认为这行不通。

【问题讨论】:

  • IMO 你不应该改变请求,你应该验证它是正确的,如果没有抛出 400。UI(或任何调用你的 API)应该进行舍入。跨度>
  • 您可以设置验证以允许以 0 或 5 结尾的数字作为 5 的倍数以 0 或 5 结尾。stackoverflow.com/questions/16557754/…
  • 您可能需要一个自定义验证属性类,在 IsValid() 方法中测试 cost % 5 == 0。阅读 C# 中的模运算符。

标签: c# asp.net .net asp.net-core-webapi


【解决方案1】:

试试:

public class MultipleOf5Attribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        return ((int)value) % 5 == 0;
    }
}

使用小数而不是整数

【讨论】:

  • 我应该在哪里实现这个类?在产品模型类中还是在单独的类中?
  • 您的答案可以通过额外的支持信息得到改进。您可以指出一个参考说明为什么最好使用小数来表示货币值。您可以详细说明必须如何使用属性。而不是“使用小数而不是 int”,您应该声明您的意思是小数类型,因为不是每个人都知道这甚至存在。
【解决方案2】:

您可以将成本变量设置为prop,然后将用户给定的任何值四舍五入,直到它有效为止。

【讨论】:

    【解决方案3】:

    您可以在视图末尾使用 JS,这可能会更好,因为您将进行前端验证,而不是在检查表单是否错误之前发布表单(抱歉,我正在使用手机输入建议的答案,所以可能格式不正确)但类似这样:

             <script>
                           document.getElementById("Submit_btn_id").addEventListener('click',function ()
                       {
    
                        //get the value entered in the input field 
                         var userEnterANumber = document.getElementById('input_id').value
    
    
                           if (userEnterANumber % 5 == 0)
                          {
                         console.write('This is a multiple of 5')
                             //turn off the required attribute from the input field 
                            document.getElementById("input_id").required = false;
                            }
       
                            else 
                            {
                              console.write('Not a multiple of 5')
                              //set the required attribute on the input field 
                            document.getElementById("input_id").required = true;
                              }
                            });
                    </script>
    

    【讨论】:

    • 并非所有帖子都使用前端完成,但这是一个很好的建议 - 始终检查用户输入!
    • 对不起,我没有使用View,我使用的是WebAPI项目解决方案,所以这需要在服务器端完成。
    猜你喜欢
    • 2016-07-17
    • 1970-01-01
    • 2011-12-12
    • 1970-01-01
    • 2011-12-03
    • 2012-02-28
    • 1970-01-01
    • 2019-01-04
    • 1970-01-01
    相关资源
    最近更新 更多