ChevCast
ChevCast

Reputation: 59213

My layout view won't recognize my BaseModel object

I followed the instructions in this blog post to create a strongly-typed view model for my _layout.cshtml file because I hate using ViewBag. Here is my base controller that all my other controllers inherit from:

public class BaseController : Controller
{
    protected BaseViewModel ModelBase { get; private set; }

    protected override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        var contextItems = filterContext.HttpContext.Items;
        if (contextItems["ModelBase"] == null)
            filterContext.HttpContext.Items["ModelBase"] = this.ModelBase;

        base.OnResultExecuting(filterContext);
    }

    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        this.ModelBase = new BaseViewModel
        {
            Theme = Request.QueryString["theme"] ?? "cyborg"
        };
        base.OnActionExecuting(filterContext);
    }
}

All I'm trying to do is grab a query string variable called "theme" and add it's value to the Theme property on BaseViewModel. According to the blog post I should be able to do @ModelBase.Theme in the layout view but I get no intellisense and it throws an error when I run it.

Upvotes: 0

Views: 186

Answers (2)

Marko
Marko

Reputation: 13243

I think you need a custom razor view base class as described in Phil Haack's post here:

http://haacked.com/archive/2011/02/21/changing-base-type-of-a-razor-view.aspx

Upvotes: 1

Kevin Nacios
Kevin Nacios

Reputation: 2853

You have to use @model BaseViewModel to strongly type your model in the view. Then you can use @Model.Theme

Upvotes: 0

Related Questions