1,导航区域通过母版页或者用户控件代理。
这部分通过读取后台提供的目录信息,动态生成链接,
目录信息包括controller,action,className以及其他属性。
大致的一个类为:
public class NavigationEntity
{
public string ControllerName { get; set; }
public string ActionName { get; set; }
public string Name { get; set; }
public string ClassName { get; set; }
}
view的代码为:
<ul id="menu">
<% foreach (navigation.Helper.NavigationEntity entity in (ViewData["navigation"] as IList<navigation.Helper.NavigationEntity>))
{ %>
<li>
<%: Html.ActionLink(entity.Name, entity.ActionName, entity.ControllerName, new { @class=entity.ClassName})%>
</li>
<%} %>
</ul>
2,使用自定义ActionFilterAttribute提供导航信息。
优点在于:
1,每个链接对应一个action,这里可以访问实际的controller,action名称。
可以往ViewData扔数据。
2,每个自定义ActionFilterAttribute可以有自己的导航信息集,
即是可以决定包含那些可用controller,action。从模块或者功能块自管理自己的
导航菜单来说,方便控制。
3,利用了FilterAttribute的方便性。
ActionFilterAttribute的四个切入时机,随便选除了OnResultExecuted的其他三个中某一个。
public class NavigationAttibute : ActionFilterAttribute
{
private IList<NavigationEntity> _navigationColletion;
private const string _selectedClassName = "higthLight";
private const string _unSelectedClassName = "unLight";
public NavigationAttibute()
{
_navigationColletion = new List<NavigationEntity>();
_navigationColletion.Add(new NavigationEntity()
{
ControllerName = "Home",
ActionName = "Index",
ClassName = _unSelectedClassName,
Name = "主页"
});
_navigationColletion.Add(new NavigationEntity()
{
ControllerName = "Home",
ActionName = "About",
ClassName = _unSelectedClassName,
Name = "关于"
});
}
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
base.OnResultExecuting(filterContext);
string controller = filterContext.RouteData.Values["controller"] as string;
string action = filterContext.RouteData.Values["action"] as string;
foreach (NavigationEntity entity in _navigationColletion)
{
if (entity.ControllerName == controller && entity.ActionName == action)
{
entity.ClassName = _selectedClassName;
}
else
{
entity.ClassName = _unSelectedClassName;
}
}
filterContext.Controller.ViewData["navigation"] = _navigationColletion;
}
}
3,在action中用起来
public class HomeController : Controller
{
[NavigationAttibute]
public ActionResult Index()
{
ViewData["Message"] = "欢迎使用 ASP.NET MVC!";
ViewData["Position"] = RouteData.Values["controller"]+"_"+RouteData.Values["action"];
//是否能取到,取决于 NavigationAttibute
IList<NavigationEntity> list = ViewData["navigation"] as IList<NavigationEntity>;
return View();
}
[NavigationAttibute]
public ActionResult About()
{
ViewData["Position"] = RouteData.Values["controller"] + "_" + RouteData.Values["action"];
//是否能取到,取决于 NavigationAttibute
IList<NavigationEntity> list = ViewData["navigation"] as IList<NavigationEntity>;
return View();
}
}
本实例改写自vs2010自动生成的asp.net mvc 2.0程序。css文件需要调整,因为css文件写了ul li.a的各种样式。不改,效果不明显。