asp.net mvc - Where is the right place for this sort of logic? -
i doing teach-yourself mvc, , have come against difficulty. database has table beers, , table breweries. naturally there foreign key constraint ensure beer has brewery. constraint "no action" constraint, intended prevent brewery being deleted if there beers brewery in database.
i implementing index page breweries, , automatically-generated code lists breweries along edit, details , delete. far, good. if attempt made delete brewery has beers, delete fails owing foreign key constraint.
but seems better withhold delete option when can't succeed. leads code in view 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 me model design leaking out view, can't see alternative; delete link must displayed or not , view has this.
how ought sort of thing tackled?
there hardly problem 'leaking'. if view needs data, , data available in model, there no problem access data. common thing.
still, if you'd rather not access .beers collection in view, add property bool hasbeers brewery viewmodel. can set property in controller , use in view, view not access more info want access.
example code:
public class breweryviewmodel { public bool hasbeers { get; set; } // other properties } public class brewerycontroller { public actionresult index() { var breweryvm = ... var beers = ... breweryvm.hasbeers = beers.any(); return view(breweryvm); } }
Comments
Post a Comment