这样可以让你在每个View中独立设定页面标题(Title),不过这样的弊端就是假如我的页面标题是如下形式"/>
技术开发 频道

Asp.net MVC中页面标题的新解决方法

  首先定义每个Controller的父类如下:

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字串就可以了

0
相关文章