2010-11-01 36 views
0

我有一个母版页,它依赖于来自我的页面的特定模型。因此,对于基本结束码每一个的ViewResult结束了这样的事情重复使用冗余视图模型代码mvc

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是通用的,有很多其他的行动使用不同的视图模型。我只是想根据它在推动时的外观来展示。

+0

使用继承:

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

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

然后所有的控制器从基本继承。你可能会把自己画到一个角落里。 :) – bzlm 2010-11-01 08:03:20

+0

继承对于MasterPage/Content Page动态是必需的。我的主页面依赖于ClientModel,而我的View页面可以采用可选的PageModel,。该解决方案效果很好。 – 2010-11-01 21:41:54

回答

1
protected ViewResult ClientModelView<T>(T model) 
{ 
    var clientModel = new ClientModel<T>(model) 
     { 
      UserNotifications = new UserNotificationModel(CurrentUser) 
     }; 

    return this.View(clientModel); 
} 
+0

这是解决我的问题,为什么downvote – 2010-11-01 15:15:06

0

查看我的类似question。这里谨慎

public class NewController : BaseController 
{ 

    public ActionResult Details(long store_id) 
    { 

     var model = GetModel(); 

     return View(model); 
    } 

} 
+0

这侧重于模型,而我试图抽象视图,并允许任何类型的模型 – 2010-11-01 15:15:34