In ASP.NET MVC, how to make a partial view available to all controllers?

In ASP.NET MVC, how to make a partial view available to all controllers? I want to create a navigation that is common to the whole site, but when I put Html.Action in my main page, it only works with views associated with 1 controller.

I currently have a controller action defined as follows:

    // GET: GetCategoriesPartial
    [ChildActionOnly]
    public ActionResult GetCategoriesPartial()
    {
        var category = CategoriesDataContext.GetCategories();
        return PartialView(category);
    }

And I created my partial view as follows:

<%@ 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 is as follows:

<%@ 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>

, -, Controller. , , :

System.Web.HttpException: "GetCategoriesPartial" "wopr.Controllers.GamesController".

?

. Quakkels

+3
3

MVC2 . , , . views ( ), . , ViewData - , , .

<% Html.RenderAction( "GetCategoriesPartial", "Category" ) %>

<%= Html.Action( "GetCategoriesPartial", "Category" ) %>
+2

views\shared

, , , - . <%=Html.Action%> . <%=Html.RenderPartial("ViewName")%>

+3

ropstah, asp.net-mvc , ( ) , .

+1
source

Source: https://habr.com/ru/post/1744554/


All Articles