ASP.NET MVC Access model data in masterpage

Posted by Paul on Stack Overflow See other posts from Stack Overflow or by Paul
Published on 2010-05-12T18:03:17Z Indexed on 2010/05/12 18:04 UTC
Read the original article Hit count: 164

Filed under:

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>() 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?

© Stack Overflow or respective owner

Related posts about asp.net-mvc-2