mardi 10 décembre 2019

If block not being executed

I am creating a car renting app with .net core. I have functionality that allows users to rent cars but I'm not finding a way how to prevent users from renting the same car. This is RentController:

 [HttpGet]
    public IActionResult Create(int id)
    {
        ViewData["IsRented"] = false;
        return View(new Rent { CarId = id, UserId = GetCurrentUserId(), 
            DateTaken = DateTime.Today});
    }

    // POST: Rents/Create
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("RentId,CarId,UserId,DateTaken,ReturnDate")] Rent rent)
    {
        if (RentExists(rent.Id))
        {
            ViewData["IsRented"] = true;
        }
        else if (ModelState.IsValid) 
        {
            _context.Rent.Add(rent);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(rent);
    }

    private bool RentExists(int id)
    {
        return _context.Rent.Any(e => e.Id == id);
    }

And Create.cshtml to rent a new car:

@if ((bool)ViewData["IsRented"])
{
    <div class="alert alert-danger" role="alert">
        This car is rented!
    </div>
}

The idea here is this: if there's already a rented car id display an error (car is rented!) and not allow user to rent it. If not then the user is able to rent it, so to create new rent. Obviously sth's not working because ViewData["IsRented"] = true; is not being executed. What is wrong with it or is there any other approach to achieve this?

Aucun commentaire:

Enregistrer un commentaire