I'm new to asp.net MVC, I decided to build an ATM web APP without any database for learning purposes. I'm figuring out the MVC pattern, for the most part, I got it working but I need help with validating the entered withdrawal amount and displaying the correct error message if incorrect data is entered. Thanks.
Also, the logic where I check if the transactions the user has completed. ''' emp.TransactionBal <= 10 ''' but the condition keeps going down to 0, - 1, -2 and so on. But I want it to stop at 0. Thanks
public class WithdrawController : Controller
{
WithdrawRepository rep = new WithdrawRepository();
[BindProperty]
public InputModel Input { get; set; }
//
// GET: /Withdraw/
public ActionResult Index()
{
IEnumerable<Withdraw> obj = rep.SelectAllWithdraws();
return View(obj);
}
// GET: /Withdraw/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Withdraw/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Withdraw emp)
{
foreach (var obj in rep.SelectAllWithdraws())
{
emp.WithdrawId = obj.WithdrawId;
emp.WithdrawDate = DateTime.Now;
emp.TransactionBal = obj.TransactionBal;
emp.AccountBal = obj.AccountBal;
emp.User= obj.User;
emp.UserID = obj.UserID;
}
try
{
//Check if user have enough cash for withdraw
//Check if the transaction is not more than 1000
//Check if the user have not exceeded 10 transaction that day
if (ModelState.IsValid && (emp.AccountBal - Input.WithdrawAmt) > 0)
{
if (Input.WithdrawAmt <= 1000 && emp.TransactionBal <= 10)
{
emp.WithdrawId ;
emp.TransactionBal--;
emp.AccountBal -= Input.WithdrawAmt;
rep.Add(emp);
return RedirectToAction("Index");
}
}
}
catch
{
ModelState.AddModelError("", "Unable to complete the transaction. "
"Try again, and if the problem persists "
"see your system administrator.");
}
return View();
}
public class InputModel: Withdraw
{
}
Create.cshtml
<div >
<div >
<form method="post">
<div >
<label asp-for="WithdrawAmt">Amount</label>
<input asp-for="WithdrawAmt" />
<span asp-validation-for="WithdrawAmt" class = "text-danger"></span>
</div>
<button >Create</button>
</form>
</div>
</div>
Model Class Withdraw.cs
public class Withdraw
{
public int WithdrawId { get; set; }
[Required]
public double WithdrawAmt { get; set; }
public int TransactionBal { get; set; }
public DateTime WithdrawDate { get; set; }
public double AccountBal { get; set; }
}
CodePudding user response:
try adding error when your if condition is failing. something like this.
try
{
//Check if user have enough cash for withdraw
//Check if the transaction is not more than 1000
//Check if the user have not exceeded 10 transaction that day
if (ModelState.IsValid && (emp.AccountBal - Input.WithdrawAmt) > 0)
{
if (Input.WithdrawAmt <= 1000 && emp.TransactionBal <= 10)
{
emp.WithdrawId ;
emp.TransactionBal--;
emp.AccountBal -= Input.WithdrawAmt;
rep.Add(emp);
return RedirectToAction("Index");
}
}
else
{
ModelState.AddModelError("WithdrawAmt","Not enough balance")
return View(emp);
}
}