.Net MVC3 Getting a Reference to the Page from a C

2019-08-04 11:03发布

问题:

What I'd like to do seems pretty simple. I'd like to specify the page title in my @Page directive on a view, like so:

<%@ Page Title="About This Site" ... %>

Then, I'd like to get that page title into the ViewData, so that it could be used in the master page, like:

<head>
    <title>The Awesome Site | <%=ViewData["Title"]%></title>

And also in the View itself like:

<h1><%=ViewData["Title"]%></h1>

I am already inheriting a custom controller for all of the page controller methods. So I'm hoping that there's something I can do in the controller to transfer the Page.Title property into the ViewData (or maybe I'll use the ViewBag). I just can't seem to find any route to reference the Page from within the Controller.

Is this possible? Is there a different approach I might want to consider.

回答1:

See "generic errors" post on this for a clean way to do this.

Passing data to Master Page in ASP.NET MVC

you should not be referencing anything from a "page" from a controller. The two are completely separate by design. You need to package your data and then send it to the view. Another way (more like what you are requesting) is that you use @{

ViewBag.Title ="my view title"; } Then the master page uses that value wherever you want it.



回答2:

I think you might be looking for Html.Title().

You can write this to any part of the page:

<title><%: Html.Title() %></title>

This will pickup the title from your view and insert it into your master page as required.