[英]ModelState Validation not working asp.net MVC
我是asp.net MVC的新手,我決定構建一個沒有任何數據庫的ATM web APP用於學習目的。 我正在弄清楚 MVC 模式,在大多數情況下,我得到了它的工作,但我需要幫助來驗證輸入的提款金額並在輸入不正確的數據時顯示正確的錯誤消息。 謝謝。
此外,我檢查用戶是否已完成交易的邏輯。 ''' emp.TransactionBal <= 10 ''' 但條件一直下降到 0、- 1、-2 等等。 但我希望它停止在 0。謝謝
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
{
}
創建.cshtml
<div class="row">
<div class="col-md-6">
<form method="post">
<div class="mb-3">
<label asp-for="WithdrawAmt">Amount</label>
<input asp-for="WithdrawAmt" class="form-control" />
<span asp-validation-for="WithdrawAmt" class = "text-danger"></span>
</div>
<button class="btn btn-success">Create</button>
</form>
</div>
</div>
模型類 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; }
}
當您的 if 條件失敗時嘗試添加錯誤。 像這樣的東西。
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.