In ASP.NET MVC, How do I make a partial view available to all controllers?
- by Quakkels
In ASP.NET MVC, How do I make a partial view available to all controllers? I want to create navigation that is common across the entire site, but when I place the Html.Action into my master page, it only works on views associated with 1 controller.
Right now, I have a controller action defined like this:
// GET: GetCategoriesPartial
[ChildActionOnly]
public ActionResult GetCategoriesPartial()
{
var category = CategoriesDataContext.GetCategories();
return PartialView(category);
}
And I've created my partial view like this:
<%@ Import Namespace="wopr.Models" %>
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<ul>
<%
foreach (var cat in Model as IEnumerable<Category>) {
%>
<li><a href="/categories/Details/<%=cat.catID%>"><%=cat.catName%></a></li>
<%
}
%>
</ul>
My Master Page looks like this:
<%@ Import Namespace="wopr.Models" %>
<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>
<link type="text/css" rel="Stylesheet" href="/Content/Site.css" />
</head>
<body>
<div class="wrap-all">
<div style="text-align:right;">
<a href="/">Home</a> |
<a href="/games/">Games</a> |
<a href="/games/Index2/1">Games <em>(paginated)</em></a> |
<a href="/categories/">Categories</a> |
<a href="/upload/">Upload</a>
</div>
<asp:ContentPlaceHolder ID="MainContent" runat="server">
</asp:ContentPlaceHolder>
<!--This errors on any non-CategoryController page.-->
<%= Html.Action("GetCategoriesPartial")%>
<!---->
</div>
</body>
</html>
This code works as long as I'm viewing something handled by the CategoriesController. If I go to any view handled by a different controller, I get the exception:
System.Web.HttpException: A public action method 'GetCategoriesPartial' was not found on controller 'wopr.Controllers.GamesController'.
How do I make this partial view available to all the site's controllers?
Thanks for any help.
Quakkels