0

I am unable to find any topics online for what I am trying to do and my attempts so far are not working.

I want the user to enter both Price and Discount using a form. The discount is not a set amount, but it should be minimum 18% of the price entered.

The model is as follows:

   [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; }

My view is:

<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>

My controllor is:

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");
    }
}

I want the validation message to appear if the user enters less than 18% of the cost. Any guidance will be appreciated.

Ainness
  • 3
  • 2

2 Answers2

0
if(loan.Discount/loan.Price<0.18)
{
  // notify user
}

Should be the formula for the condition. If price is or is changed to integer, cast it in the division with a (float) for example.

Miro Krsjak
  • 355
  • 1
  • 16
  • Thanks. It's working now. My original code is working now also with no change to code. Thanks again. – Ainness Jan 22 '17 at 16:51
0

See custom validators

You can implement your custom logic inside them and use them as any other validator

Community
  • 1
  • 1
Anestis Kivranoglou
  • 7,728
  • 5
  • 44
  • 47