Reputation: 127
I feel like this should be easy... but I am having trouble. I need to compare a value entered by the user to a value that exists in my database. If "available" is less than the value requested by the user, the request should terminate and display an error message. My POST action has an if statement like this:
var cardcollection = new CardCollection { CardCollectionID = 0, CollectionID = 0, CardID = 0, NumberofCopies = 0, Wishlist = 0, Available = 0, InDecks = 0 };
cardcollection = db.CardCollections.Where(c => c.CardID.Equals(cardid)).Where(d => d.CollectionID.Equals(collectionid)).First();
int num = number.NumberToAdd;
int copies = cardcollection.NumberofCopies;
int available = cardcollection.Available;
if (num > available)
{
// Pass message "Cannot add more than is available in your collection";
//return View(GO BACK TO CREATE VIEW);
}
available = copies - num;
int used = cardcollection.InDecks;
int indecks = used + num;
int id = cardcollection.CardCollectionID;
for (int i = 0; i < num; i++)
{
db.CardDecks.Add(carddeck);
db.SaveChanges();
}
var cardavailability = String.Format("Update CardCollections Set InDecks = {0}, available = {1} Where CardCollectionID = {2}", indecks, available, id);
db.Database.ExecuteSqlCommand(cardavailability);
db.SaveChanges();
return RedirectToAction("Details", "Deck", new { id = deckid });
I can't use the ModelState.IsValid because it is already valid.
Upvotes: 0
Views: 63
Reputation: 6981
What about using ModelState.AddModelError:
if (num > available)
{
ModelState.AddModelError("MyError","Cannot add more than is available in your collection");
return View(GO BACK TO CREATE VIEW);
}
Then in the view:
@Html.ValidationMessage("MyError")
Upvotes: 2