How to do server-side validation using MVC 5
Asked Answered
I

2

6

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.

Immigrate answered 20/2, 2014 at 14:43 Comment(2)
Just in addition, you should do the RedirectToAction after db.SaveChanges. You should not use RedirectToAction if the ModelState is not valid. You want to return the view and pass the model to preserve any validation messages and keep the state as it was. Redirecting will lose any validation messages in the ModelState.Seaborne
@DavidSpence Hi David. Not sure I followed that. Can you post the amended code? Thanks.Immigrate
P
16

You should have a look at the AddModelError method of the ModelState property.

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

@Html.ValidationSummary(true)
Primordial answered 20/2, 2014 at 14:49 Comment(1)
Or you could use ModelState.AddModelError(string.Empty,"Already outbid");Lalonde
R
0

For a better understanding of server-side validation a code snippet of movie name validation in server side is given below

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult CreateMovie(Movie movie)
    {
        var userExist = _context.Movies.Where(l => l.Name == movie.Name ).FirstOrDefault();

        if (userExist != null )
        {
            ModelState.AddModelError("error", "This Movie  Name is already registered");
            return View();
        }

        if (ModelState.IsValid)
        {
            _context.Movies.Add(movie);

            try
            {
                _context.SaveChanges();

            }
            catch (DbEntityValidationException e)
            {
                Console.WriteLine(e);
            }


        }

        return RedirectToAction("Index", "Movies");
    }

and don't forget to add in view the following code snippet

@Html.ValidationMessage("error", new { @class = "text-danger" })
Rattlehead answered 25/11, 2019 at 17:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.