拋棄TitleContent – Asp.net MVC中頁面標題的新解決方案

來源:互聯網
上載者:User

在Asp.net MVC 1.0正式版中的模板頁中提供了:

<asp:ContentPlaceHolder ID="TitleContent" runat="server" />

這樣可以讓你在每個View中獨立設定頁面標題(Title),不過這樣的弊端就是假如我的頁面標題是如下形式:

統一標題 - 副標題

那麼要在每個View中都寫上:

日記頁面:

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    CaraQ - 日記
</asp:Content>

相簿頁面:

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    CaraQ - 相簿
</asp:Content>

……

假如有一天我要把其中的統一標題改一下那就得一個頁面一個頁面的去改,太過麻煩,而且這種命名標題的方法我認為也有背MVC的精神--讓控制器決定視圖顯示的內容

其實有更簡單的實現方法,如下:

首先定義每個Controller的父類如下:

{
this.style.display='none'; document.getElementById('Code_Closed_Text_092039').style.display='none'; document.getElementById('Code_Open_Image_092039').style.display='inline'; document.getElementById('Code_Open_Text_092039').style.display='inline';
}" id="Code_Closed_Image_092039" style="display: none">{
this.style.display='none'; document.getElementById('Code_Open_Text_092039').style.display='none'; getElementById('Code_Closed_Image_092039').style.display='inline'; getElementById('Code_Closed_Text_092039').style.display='inline';
}" id="Code_Open_Image_092039">Code
 public class BaseController : Controller
 {
        private readonly string _titleFormat = "CaraQ - {0}";
        private string _title;

        protected string Title
        {
            get { return _title; }
            set { _title = value; }
        }

protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            ViewData["Title"] = string.Format(_titleFormat, Title);
            base.OnActionExecuted(filterContext);
        }
}

 

讓所有的Controller繼承這個父類,設定頁面標題的方法只需要在Action中使用如下方式即可:

 

public class BlogController : BaseController
{
    public ActionResult Index()
    {
        this.Title = "日記";
    }
}

 

最後在模板頁中把TitleContent佔位控制項換成:

<%=ViewData["Title"] %>

 

這樣就可以了,看到這樣給頁面命名標題是不是就簡單多了,在View中了不會有那個像

<asp:Content ID="titleContent" ContentPlaceHolderID="TitleContent" runat="server"></asp:Content>

的控制項了,要修改統一標題時只需要修改BaseController中的_titleFormat字串就可以了

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.