【问题标题】:reuse redundant view model code mvc重用冗余视图模型代码 mvc
【发布时间】:2010-11-01 04:33:31
【问题描述】:

我有一个母版页,它依赖于来自我的页面的特定模型。所以基本上每个 ViewResult 的结束代码都是这样的

public ActionResult Details(long store_id)
{
    var store = getStore();

    var model = new ClientModel<StoreModel>(store)
        {
            UserNotifications = new UserNotificationModel(this.CurrentUser)
        };

    return View(model);
}

我的每个控制器都派生自一个 BaseController,因此我希望将这些冗余代码放在那里,但我不确定最好的方法。

我的通用 ClientModel 的结构是这样的......

public class ClientModel<T> : ClientModel {}

public class ClientModel {}

澄清 StoreModel 是通用的,许多其他操作使用不同的视图模型。我只是想根据执行时的外观来展示。

【问题讨论】:

  • 在此处谨慎使用继承。你可能会把自己画到一个角落里。 :)
  • 继承对于 MasterPage / Content Page 动态是必要的。我的母版页依赖于 ClientModel,而我的视图 Pages 可以采用可选的 PageModel,即 。该解决方案效果很好。

标签: asp.net-mvc


【解决方案1】:
protected ViewResult ClientModelView<T>(T model)
{
    var clientModel = new ClientModel<T>(model)
        {
            UserNotifications = new UserNotificationModel(CurrentUser)
        };

    return this.View(clientModel);
}

【讨论】:

    【解决方案2】:

    看看我类似的question

    基本上,您创建一个基本控制器:

    public class BaseController : Controller
    {
        public Model GetModel() {}
    }
    

    那么你所有的控制器都从基础继承:

    public class NewController : BaseController
    {
    
        public ActionResult Details(long store_id)
        {
    
            var model = GetModel();
    
            return View(model);
        }
    
    }
    

    【讨论】:

    • 这专注于模型,而我试图抽象视图,并允许任何类型的模型
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多