views:

1015

answers:

2

My View is strongly typed to an ADO.NET Entity Framework class with a boolean property ShowMenu.

<%@ Page ... MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage(Of Thing)" %>
...

I want to do something like this on my Master Page...

<%@ Master ... Inherits="System.Web.Mvc.ViewMasterPage" %>
...
<div id="menu" runat="server" visible="<%= Me.Page.Model.ShowMenu %>">
    <asp:ContentPlaceHolder ID="MenuContent" runat="server" />
</div>

But, I get this error:

'Model' is not a member of 'System.Web.UI.Page'

How can I access a View's Model from its Master Page?


Update

Oops:

Server tags cannot contain <% ... %> constructs.

Have to use If...Then instead.

+7  A: 

You can't do that. What you need to do is have your master page view model set, like this:

Inherits="System.Web.Mvc.ViewMasterPage<BaseModel>"

...where BaseModel is some base class that you'll use in EVERY SINGLE view. because of this restriction, it's pretty brittle and you might not want to do it.

In any case, then every single view has to be have a model type that derives from BaseModel.

Then in your master page you can simply do:

<%= Model.ShowMenu %>

Another option is to use the ViewData dictionary and have a sensible default value in case the action didn't set it.

<% if( (bool)(ViewData["showmenu"] ?? false) ) { %>
    ... render menu here ...
<% } %>

This is pretty ugly, so you might instead choose to use a helper:

<% if(this.ShouldRenderMenu()) { %>
   .....
<% } %>

and in your helper:

public static class MyExtensions
{
   public static bool ShouldRenderMenu(this ViewMasterPage page)
   {
      return (bool)(page.ViewData["rendermenu"] ?? false);
   }
}
Ben Scheirman
Worked flawlessly for me. Thanks!
MK_Dev
A: 

I'm not sure why he deleted it, but Rajesh Pillai's answer works:

Me.ViewData.Model.ShowMenu
Zack Peterson
That doesn't work unless the master page has a model type which contains a member ShowMenu.
Ben Scheirman