C# 验证依赖于用户输入的百分比
我无法在网上找到关于我正在尝试做的事情的任何主题,到目前为止,我的尝试都不起作用 我希望用户使用表单输入价格和折扣。折扣不是固定金额,但至少应为输入价格的18% 模型如下:C# 验证依赖于用户输入的百分比,c#,asp.net,visual-studio,C#,Asp.net,Visual Studio,我无法在网上找到关于我正在尝试做的事情的任何主题,到目前为止,我的尝试都不起作用 我希望用户使用表单输入价格和折扣。折扣不是固定金额,但至少应为输入价格的18% 模型如下: [Required(ErrorMessage = "Please Enter Price")] [Display(Name = "Price")] public float Price { get; set; } [Required(ErrorMessage = "Please Enter t
[Required(ErrorMessage = "Please Enter Price")]
[Display(Name = "Price")]
public float Price { get; set; }
[Required(ErrorMessage = "Please Enter the Discount. This must be minimum 15% of cost.")]
[Display(Name = "Discount")]
public float Discount { get; set; }
我的看法是:
<div class="form-group">
@Html.LabelFor(m => m.Price)
@Html.TextBoxFor(m => m.Price, new { @class = "form-control" })
</div>
<div class="form-group">
@Html.LabelFor(m => m.Discount)
@Html.TextBoxFor(m => m.Discount, new { @class = "form-control" })
</div>
@LabelFor(m=>m.Price)
@TextBoxFor(m=>m.Price,新的{@class=“form control”})
@LabelFor(m=>m.Discount)
@TextBoxFor(m=>m.Discount,新的{@class=“form control”})
我的控制器是:
public ActionResult Add(Loan loan)
{
try
{
if (loan.Discount < loan.Price / 100 * 18)
{
_dbLoan.Loans.Add(loan);
_dbLoan.SaveChanges();
return RedirectToAction("Index");
}
else
{
return ("Error");
}
}
catch
{
return View("Error");
}
}
公共行动结果添加(贷款)
{
尝试
{
如果(贷款折扣<贷款价格/100*18)
{
_dbLoan.Loans.Add(loan);
_dbLoan.SaveChanges();
返回操作(“索引”);
}
其他的
{
返回(“错误”);
}
}
抓住
{
返回视图(“错误”);
}
}
如果用户输入的成本低于18%,我希望显示验证消息。如有任何指导,我们将不胜感激。if(loan.Discount/loan.Price请参阅
if(loan.Discount/loan.Price<0.18)
{
// notify user
}
您可以在它们内部实现自定义逻辑,并将它们用作任何其他验证器谢谢。它现在可以工作了。我的原始代码现在也可以工作了,代码没有更改。再次感谢。