All articles(网络文学目录) All Pictures(图片目录) All Softwares(软件目录)

 
Asp.net,MVC中页面标题的解决方法_[Asp.Net教程]

Writer: 归海一刀 Article type: Programming skills(编程技巧) Time: 2014/1/30 1:17:20 Browse times: 296 Comment times: 0

Asp.net,MVC中页面标题的解决方法_[Asp.Net教程]


Head photo

Go homepage
Upload pictures
Write articles

Asp.net MVC中页面标题的解决方法_[Asp.Net教程] 在Asp.net MVC 1.0正式版中的模板页中提供了:
这样可以让你在每个View中独立设定页面标题(Title),不过这样的弊端就是假如我的页面标题是如下形式:统一标题 - 副标题
那么要在每个View中都写上:日记页面:

CaraQ - 日记


相册页面:

CaraQ - 相册


……
假如有一天我要把其中的统一标题改一下那就得一个页面一个页面的去改,太过麻烦,而且这种命名标题的方法我认为也有背MVC的精神--让控制器决定视图显示的内容
其实有更简单的实现方法,如下:
首先定义每个Controller的父类如下:

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中了不会有那个像
的控件了,要修改统一标题时只需要修改BaseController中的_titleFormat字串就可以了




There are 0 records,
Comment:
Must be registered users to comment(必须是注册用户才能发表评论)

Disclaimer Privacy Policy About us Site Map
Copyright ©2011-
uuhomepage.com, Inc. All rights reserved.