0
        <div class="display-label">
            <a>Contact</a>
            @(Model.Store.EmployeeType.Name == "Manager" ? Model.Store.HQ.Manager.DisplayName : Model.Store.Manager.DisplayName )
        </div>

How should null exceptions for each of these Entities be handled in the view? I have a TON of these kind of - is there an elegant way to check for nulls without doing an if statement before each one?

tereško
  • 58,060
  • 25
  • 98
  • 150
RobVious
  • 12,685
  • 25
  • 99
  • 181

1 Answers1

2

Yes, create a property on your ViewModel:

public class ManagerViewModel 
{
    public string Manager {get;set;}
}

And in your controller:

var viewModel = new ManagerViewModel();
viewModel.Manager = Model.Store.EmployeeType.Name == "Manager" ? Model.Store.HQ.Manager.DisplayName : Model.Store.Manager.DisplayName;
return View(viewModel);

Then in your view, all you need to do is:

@Model.Manager
Martin
  • 11,031
  • 8
  • 50
  • 77
  • Thanks so much. What if EmployeeType.Name is null in your case? Will the view still render? – RobVious Jan 25 '13 at 03:57
  • And - doesn't this violate the skinny controller best practice? I have about 30 fields that need this type of filtering. Is it better to have a fat controller than a fat view? – RobVious Jan 25 '13 at 04:01
  • 1
    if the `EmployeeType.Name` is `null`, it'll still render since string is already nullable. As for the skinny controller bit, take a look at my answer to your [other question](http://stackoverflow.com/a/14515512/124069). – Chase Florell Jan 25 '13 at 05:04