I am working on a simple auction website for a charity. I have an Item model for the sale items, and a Bid view where the user can enter a bid and submit it. This bid is received inside the Item controller:
我正在一个简单的拍卖网站上为一家慈善机构工作。我有一个销售项目的项目模型,以及一个用户可以输入出价并提交出价的出价视图。此出价在项目控制器内收到:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Bid(int itemID, int bidAmount)
{
if (ModelState.IsValid)
{
Item item = db.Items.Find(itemID);
if (bidAmount >= item.NextBid)
{
item.Bids++;
item.CurrentBid = bidAmount;
item.HighBidder = HttpContext.User.Identity.Name;
db.Entry(item).State = EntityState.Modified;
db.SaveChanges();
}
else
{
// Already outbid
}
return View(item);
}
return RedirectToAction("Auction");
}
I would like to know how to display server-side validation to the user. For example, in the above code, it may be that the submitted bid amount is no longer sufficient. In that case, I would like to display a message to the user that they have been outbid etc.
我想知道如何向用户显示服务器端验证。例如,在上面的代码中,提交的出价金额可能不再足够。在这种情况下,我想向用户显示一条消息,表明它们已被出价等。
How can I pass this information back to the view to display an appropriate message? I want the user to see the same item page view as before, updating the value in the edit box and displaying the message - similar to eBay. Thanks.
如何将此信息传递回视图以显示相应的消息?我希望用户看到与以前相同的项目页面视图,更新编辑框中的值并显示消息 - 类似于eBay。谢谢。
1 个解决方案
#1
13
you should have a look at the AddModelError Method of the ModelState Property.
您应该看一下ModelState属性的AddModelError方法。
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Bid(int itemID, int bidAmount)
{
if (ModelState.IsValid)
{
Item item = db.Items.Find(itemID);
if (bidAmount >= item.NextBid)
{
item.Bids++;
item.CurrentBid = bidAmount;
item.HighBidder = HttpContext.User.Identity.Name;
db.Entry(item).State = EntityState.Modified;
db.SaveChanges();
}
else
{
// Already outbid
ModelState.AddModelError("", "Already outbid");
}
return View(item);
}
return RedirectToAction("Auction");
}
To Display the message in your view, you need a ValidationSummary
要在视图中显示消息,您需要ValidationSummary
@Html.ValidationSummary(true)
@ Html.ValidationSummary(真)
#1
13
you should have a look at the AddModelError Method of the ModelState Property.
您应该看一下ModelState属性的AddModelError方法。
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Bid(int itemID, int bidAmount)
{
if (ModelState.IsValid)
{
Item item = db.Items.Find(itemID);
if (bidAmount >= item.NextBid)
{
item.Bids++;
item.CurrentBid = bidAmount;
item.HighBidder = HttpContext.User.Identity.Name;
db.Entry(item).State = EntityState.Modified;
db.SaveChanges();
}
else
{
// Already outbid
ModelState.AddModelError("", "Already outbid");
}
return View(item);
}
return RedirectToAction("Auction");
}
To Display the message in your view, you need a ValidationSummary
要在视图中显示消息,您需要ValidationSummary
@Html.ValidationSummary(true)
@ Html.ValidationSummary(真)