从View移动逻辑控制器和视图模型 [英] Moving logic from View to Controller and ViewModel

查看:106
本文介绍了从View移动逻辑控制器和视图模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将所有的定义如下所示:

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;}
}

和定义它们控制器:

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

我的问题是 - 这是否违反骨感控制最佳做法?我有大约30个字段需要这种类型的治疗,所以我的控制器将是pretty大 - 我为每一个领域的一个新的属性。

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.

推荐答案

不要太担心 premature优化。我认为你是在正确的道路上这里就不会担心太多。

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);

这篇关于从View移动逻辑控制器和视图模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆