I am doing teach-yourself MVC, and have come up against a difficulty. My database has a table for Beers, and a table for Breweries. Naturally there is a foreign key constraint to ensure a Beer has a Brewery. This constraint is a "no action" constraint, intended to prevent a Brewery from being deleted if there are Beers for that Brewery in the database.
I am implementing the Index page for the Breweries, and the automatically-generated code lists the Breweries along with Edit, Details and Delete. So far, so good. If an attempt is made to delete a Brewery that has Beers, the delete fails owing to the foreign key constraint.
But it seems better to withhold the delete option when it can't succeed. This leads to code in the View like this:-
@Html.ActionLink("Edit", "Edit", new { id=item.BreweryID }) |
@Html.ActionLink("Details", "Details", new { id=item.BreweryID })
@if(item.Beers.Count == 0)
{
<text> |</text>
@Html.ActionLink("Delete", "Delete", new { id=item.BreweryID })
}
It seems to me that the Model design is leaking out into the View, but I can't see any alternative; the Delete link must be displayed or not and the view has to do this.
How ought this sort of thing be tackled?