I have created a UserSiteBaseController that gets commonly used data and sets the data to a UserSiteBaseViewData viewmodel in a method called SetViewData
public T CreateViewData<T>() where T : UserSiteBaseViewData, new()
{
....
}
I then create specific Controllers that inherit from the UserSiteBaseController as well as viewModels that inherit from UserSiteHomeViewData and can be created in the controller like so:
public ActionResult Index(string slug)
{
Slug = slug;
var viewData = CreateUserSiteHomeViewData<UserSiteHomeViewData>();
//If invalid slug - throw 404 not found
if (viewData == null)
return PageNotFound();
viewData.Announcements = _announcementsData.All(slug).ToList();
return View(viewData);
}
private T CreateUserSiteHomeViewData<T>开发者_JAVA百科;() where T : UserSiteHomeViewData, new()
{
T viewData = CreateViewData<T>();
return viewData;
}
The UserBaseViewData holds data that needs to be use on every page so it would be great to be able to access this data from the Masterpage in a strongly typed manner. Is this possible or am I going about this in the incorrect manner?
If you get your masterpage to inherit from System.Web.Mvc.ViewMasterPage<BaseViewModel>
you should be good to go...?
BUT, when I first started using MVC I went down the same route using a BaseViewModel
class which contained all my generic ViewModel stuff and then I created specific view models, e.g. EventListingViewModel
, which inherited from this BaseViewModel
- much like you are doing. My masterpages then inherited from System.Web.Mvc.ViewMasterPage<BaseViewModel>
and everything was going swell.
But after a while it all became a bit tightly coupled and a quite brittle. It became a pain in the ass to make changes and what not. I also came across this issue.
So I've reverted back to using the standard ViewData dictionary (with a static VewDataKeys class to avoid magic strings) for all my generic properties and then using custom POCO objects that don't inherit from anything as my presentation models. This is working much better and I wouldn't change back.
HTHs,
Charles
精彩评论