Samantha J T Star
Samantha J T Star

Reputation: 32758

How can I best handle stopping deletion of a row when records exist?

I have a list of book records that shows up on my MVC Razor screen

1  edit   delete   Harry Potter 1
2  edit   delete   Harry Potter 2
..
3  edit   delete   Harry Potter 25

When a user clicks on the [delete] link then control goes to a Delete method on the controller. This then shows a MVC Razor screen which allows the user to confirm the delete (if no stock exists) or cancel the delete (if stock exists).

My question is "where should I check stock" should I check this in the Razor view with a statement like the following:

@if (@Model.xxx.Count == 0) {
   show the user a [confirm delete] button 
}

@if (@Model.xxx.Count != 0) {
   show the user a [cancel button] and a message saying "cannot delete"
}

It seems clunky to do all this in the view but also the controller doesn't quite seem the right place and if in the controller then I am not sure how to code it.

Upvotes: 1

Views: 114

Answers (2)

Martin Liversage
Martin Liversage

Reputation: 106796

You should not display a delete link in the first place if the user cannot delete the book anyway. It is much more user friendly to disallow the user to do anything before the user actually attempts doing it instead of letting the user attempt an action that you then tell him he cannot do.

So basically you need to do the Model.xxx.Count != 0 check when the list is generated. However, you still need to perform the same validation in the delete controller to avoid acting on invalid data (as you should do in any controller).

Upvotes: 2

thomaux
thomaux

Reputation: 19718

You should check stock both in the view and in your controller:

  • Your view should only display valid actions to the user, showing him a delete button that won't guarantee to actually delete a record based on some unclear reasoning makes no sense.
  • Your controller should also check whether or not it's allowed to perform the action, otherwise your controller could be accessed directly and the resource could still be deleted.

Upvotes: 3

Related Questions