Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Master Page: "'Model' is not a member of 'System.Web.UI.Page'"

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.

like image 209
Zack Peterson Avatar asked Dec 30 '22 01:12

Zack Peterson


1 Answers

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);
   }
}
like image 137
Ben Scheirman Avatar answered Jan 01 '23 13:01

Ben Scheirman