reuse redundant view model code mvc
I have a master page that relies on a specific model coming from my pages. So the ending code for basically every ViewResult ends up something like this
public ActionResult Details(long store_id)
{
var store = getStore();
var model = new ClientModel<StoreModel>(store)
{
UserNotifications = new UserNotificationModel(this.CurrentUser)
};
return View(model);
}
Each one of my controllers derives from a BaseController, so i was looking to put this redundant code there, but I'm not really sure the best approach to take.
The structure for my generic ClientModel is this...
public class ClientModel<T> : ClientModel {}
public class ClientModel {}
Clarification The StoreModel is generic and a lot of other actions use a diffe开发者_StackOverflow社区rent view model. I just wanted to show based on how it looks when impelmented.
protected ViewResult ClientModelView<T>(T model)
{
var clientModel = new ClientModel<T>(model)
{
UserNotifications = new UserNotificationModel(CurrentUser)
};
return this.View(clientModel);
}
Check out my similar question.
Basically, you create a base controller:
public class BaseController : Controller
{
public Model GetModel() {}
}
Then all your controllers inherit from the base:
public class NewController : BaseController
{
public ActionResult Details(long store_id)
{
var model = GetModel();
return View(model);
}
}
精彩评论