导航的结构
/// <summary> /// 导航面包 /// </summary> public class BannerBread { public string DisplayTitle { get; set; } public string Url { get; set; } public int ID { get; set; } public int ParentID { get; set; } public BannerBread Parent { get; set; } }
下面这段代码就是实现导航的核心,它对外提供一个唯一的访问点,所以,和两个公开的方法,一个是GetBanner,用来返回当前URL对应的导航完整对象(包括祖宗对象),GenerateStandardBanner方法返回一个标准的导航,当前,具体的项目,你可以自己
去实现它。
/// <summary> /// 导航生产类 /// </summary> public static class BannerBreadFactory { /// <summary> /// BannerBread单例实例对象 /// </summary> static readonly List<BannerBread> Instance = new List<BannerBread>(); static BannerBreadFactory() { Instance.Add(new BannerBread { ID = 1, DisplayTitle = "首页", Parent = null, ParentID = 0, Url = "/" }); Instance.Add(new BannerBread { ID = 2, DisplayTitle = "关于我们", Parent = null, ParentID = 1, Url = "/Home/About" }); Instance.Add(new BannerBread { ID = 3, DisplayTitle = "联系我们", Parent = null, ParentID = 1, Url = "/Home/Contact" }); } /// <summary> /// 得到当前URL的祖宗节点 /// </summary> /// <param name="url"></param> /// <returns></returns> public static BannerBread GetBanner(string url) { var entity = Instance.FirstOrDefault(i => i.Url.ToUpper() == url.ToUpper()); GetFather(entity); return entity; } /// <summary> /// 标准的导航,程序开发人员可以根据自己的需要,在具体项目中去定义它 /// </summary> /// <param name="url"></param> /// <returns></returns> public static string GenerateStandardBanner(string url) { var entity = GetBanner(url); StringBuilder str = new StringBuilder(); while (entity != null) { str.Insert(0, "/<span><a href='" + entity.Url + "'>" + entity.DisplayTitle + "</a></span>"); entity = entity.Parent; } return str.ToString().StartsWith("/") ? str.ToString().Substring(1) : "未找到导航项"; } /// <summary> /// 得到祖宗 /// </summary> /// <param name="son"></param> private static void GetFather(BannerBread son) { if (son != null) { son.Parent = Instance.FirstOrDefault(i => i.ID == son.ParentID); GetFather(son.Parent); } } }