开发者

Strongly typed custom baseviewdata in a custom basecontroller

In my project I have strongly typed viewdata in the spirit of the following:

AppleListViewData : ViewDataDictionary
  + SelectedTheme
  + ThemeList
  + SelectedApple
  + AppleList

Where the first four are re-occuring accross all the viewdatas because they are used in the site.master

To keep it DRY I elevated them into a BaseViewData class which the other inherit from.

Now all my controllers need to fill up these properties. Again, to keep it DRY I created a BaseController for my controllers that takes on this job.

BaseController : Controller
  + new ViewData : BaseViewDat开发者_StackOverflow中文版a
  + FetchThemes
  + FetchSelectedTheme

The BaseController.ViewData is newed because it hides the Controller.ViewData All the controllers are responsible of newing up the viewdata at constructor time.

I'm essentially hiding the existing viewdata system and replacing it with my own.

This is where I feel I'm doing something wrong. Any suggestions how I can make this work in a more elegant way?


If these items are always in your master pages, it may make sense to extract the controls which use the data and have a controller handle each one. Then in your masterpage use Html.RenderAction and output the user control with your data. This way none of your controllers get cluttered with information about the theme views, and anyone reading your code will easily see where the data comes from

Example

public class ThemeController : Controller{
  public ActionResult ThemeDropDown(){
     return PartialView(new ThemeViewModel(){ SelectedTheme = ..., ThemeList = ... })
  }
}


public class AppleController : Controller{
  public ActionResult AppleStuff(){
     return PartialView(new AppleViewModel(){ Apple = ..., AppleList = ... })
  }
}


<%= Html.RenderAction("ThemeDropDown", "Theme") %>    
<%= Html.RenderAction("AppleStuff", "Apple") %>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜