ASP.NET MVC - View with master page, how to set title?

后端 未结 11 996
旧时难觅i
旧时难觅i 2020-12-10 02:50

What is prefered way of setting html title (in head) for view when using master pages?

One way is by using Page.Title in .aspx file, but that requires in master pag

相关标签:
11条回答
  • 2020-12-10 03:30

    I see a lot of people that use the <%= ViewData["Title"] %> option.

    I suppose you could also insert a ContentPlaceHolder named Title and then just use that on your page, but in all the MVC examples I've seen, they use the first option.

    0 讨论(0)
  • 2020-12-10 03:30

    I ended up using a code-behind file to implement Page.Title="..." in the Page_Load() method.

    I didn't like doing this, however attempts to implement the change directly in the .aspx page did not work, as it resulted in two <title> tags being present, the one I generated, and the one generated by the Master file the page inherited from.

    Ideally, my page code should have overridden the master file's <title> value, but I guess this is just one of those quirks that ASP.Net MVC still has, and one that may already be fixed in a newer version of the ASP.Net MVC Framework (we're still on ASP.Net MVC Beta)

    0 讨论(0)
  • 2020-12-10 03:32

    For ASP.NET content pages just add Title="" in the <%@ %> Placeholder.

    0 讨论(0)
  • 2020-12-10 03:36

    You could always use javascript in your view page:

    <script type="text/javascript>
        document.title = "Hello World";
    </script>
    
    0 讨论(0)
  • 2020-12-10 03:37

    In our master pages, we created both an "init" ContentPlaceHolder, and a "title" ContentPlaceHolder. If someone wants to programatically set Page.Title, they can set it in CSharp in the init placeholder, or they can override the "title" placeholder using tags.

    Master Page

    <asp:ContentPlaceHolder id="init" runat="server"></asp:ContentPlaceHolder>
    <head runat="server">    
        <asp:ContentPlaceHolder ID="title" runat="server">
            <title><%=this.Page.Title%></title>
        </asp:ContentPlaceHolder>
    </head>
    

    View Page Could either override the entire "title" content placeholder:

    <asp:Content ID="Content1" ContentPlaceHolderID="title" runat="server">
           <title>Home Page</title>
    </asp:Content>
    

    or programatically set the page title.

    <asp:Content ID="Content1" ContentPlaceHolderID="init" runat="server">
        <%this.Title = "Home Page";%>
    </asp:Content>
    

    Make sure you remove the Title="" from the Page directive at the top, or you won't be able to programatically change Page.Title.

    0 讨论(0)
提交回复
热议问题