Moving logic from View to Controller and ViewModel

2019-06-11 07:12发布

问题:

I'm moving all definitions like the following:

 @(Model.Store.EmployeeType.Name == "Manager" ? Model.Store.HQ.Manager.DisplayName : Model.Store.Manager.DisplayName )

Out of my View and into a viewModel:

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

And defining them in the controller:

var viewModel = new ManagerViewModel();

viewModel.Manager = Model.Store.EmployeeType.Name == "Manager" ? Model.Store.HQ.Manager.DisplayName : Model.Store.Manager.DisplayName;

return View(viewModel);

Now, in my View I can do this:

@Model.Manager

My question is - does this violate the skinny controller best practice? I have about 30 fields that need this type of treatment, so my controller is going to be pretty big - I'm creating a new property for every field.

回答1:

Don't worry too much about premature optimization. I think you're on the right path here and wouldn't worry too much about it.

You could populate the ViewModel from within the Constructor if you're really worried about "skinny" controllers.

public class ManagerViewModel 
{

    public ManagerViewModel(ManagerModel model){
        // initialize in here
        this.Manager = model.Store.EmployeeType.Name == "Manager" ? model.Store.HQ.Manager.DisplayName : model.Store.Manager.DisplayName;
    }

    public string Manager {get;set;}
}
var viewModel = new ManagerViewModel(model);
return View(viewModel);