In the previous article we completed the dynamic generation of multi-level menus, the utility component.
In this article we are going to develop another useful component: Breadcrumb navigation.
Breadcrumb navigation (breadcrumbnavigation) This concept comes from the fairy tale "Hansel and Gretel", when Hansel and Gretel through the forest, accidentally lost, but they found that along the way through the place has been sprinkled crumbs, let these crumbs to help them find the road home. So, the role of breadcrumb navigation is to tell visitors where they are currently in the site and how to return. (Excerpt from Baidu Encyclopedia)
To enable breadcrumb navigation, you can also search directly from NuGet for some sitemap components.
Of course, as in the previous article, we also do not have any third-party components, completely build our own flexible and universal Sitemap.
Here's my best practice.
Article outline
Third, build HTML helper, complete breadcrumb generation function
Iv. Front-end invocation
Overview Highlights
The breadcrumb navigation is divided into two steps:
1. Obtain the current URL address, according to the URL address to the relevant configuration file query to the current location, recursive query parent node
2. Dynamically stitching out breadcrumb HTML based on the results of the query
If you read the previous article should be familiar with the technology used in this article (more simple than the previous article:))
We are directly stitching out the HTML based on the site's configuration, and the front end gets the stitched content by customizing the HTML helper's method call.
on how to customize HTML helper, the previous article was introduced and no longer duplicated.
Detailed steps are explained directly below.
Detailed steps
Divided into four steps
I. Analyzing the HTML structure of multilevel catalogs
First open a sample, such as
The corresponding HTML is
As you can see, it consists of two layers, the outside is a <ol>, and inside is a group of <li>.
Each <li> contains a <a> tag that points to the appropriate location address.
The last <li> does not include the <a> tag, only the name is displayed.
The site map source and corresponding data model of XML based on HTML structure
1. Based on the HTML structure above, we prepare the data source for the Sitemap.
In general, the site map does not involve permissions, and will not change frequently, such as the site of a location is not configured, directly do not display, there will be no other impact.
So for simplicity's sake, just prepare an XML document.
<?xml version= "1.0" encoding= "Utf-8"?>
<!--fill in absolute path, similar to/xengine/home/about-->
<MvcSiteMaps>
<mvcsitemap Parnetid = "0" Name = "Home" URL = "/xengine/" ID = "1" ></MvcSiteMap>
<mvcsitemap Parnetid = "1" Name = "organization" URL = "/xengine/organization" ID = "2" ></MvcSiteMap>
<mvcsitemap Parnetid = "2" Name = "about" URL = "/xengine/home/about" ID = "3" ></MvcSiteMap>
</MvcSiteMaps>
In the end we just need to populate the XML with the corresponding values into the breadcrumb HTML
2. Prepare the corresponding data model
[XmlRoot ("Mvcsitemaps")]
public class Mvcsitemaps
{
[XmlElement ("Mvcsitemap")]
Public mvcsitemap[] Items {get; set;}
}
public class Mvcsitemap
{
[XmlAttribute (AttributeName = "ID")]
public int ID {get; set;}
[XmlAttribute (AttributeName = "Name")]
public string Name {get; set;}
[XmlAttribute (AttributeName = "Url")]
public string Url {get; set;}
[XmlAttribute (AttributeName = "Parnetid")]
public int Parnetid {get; set;}
Public Mvcsitemap Parent {get; set;}
}
Note [XmlAttribute (AttributeName = "xxx")],attributename need to correspond to the name in the XML, our XML and the data model are named exactly, so we can also omit.
Third, build HTML helper, complete breadcrumb generation function
You need to complete the following functions
1. Get all the node information in the XML
private static string sitemapstring = system.configuration.configurationmanager.appsettings["sitemapstring"]?? String. Empty;
Get configuration information for a Sitemap
public static ilist<mvcsitemap> Getsitemaplist ()
{
using (TextReader reader = new StreamReader (HttpContext.Current.Server.MapPath (sitemapstring)))
{
var serializer = new XmlSerializer (typeof (Mvcsitemaps));
var items = (mvcsitemaps) serializer. Deserialize (reader);
if (items! = null)
{
return items. Items;
}
return null;
}
}
2. Based on the node information obtained in the previous step and the current URL address, stitching the breadcrumb HTML
<summary>
Filling bread crumbs
</summary>
<param name= "url" ></param>
<returns></returns>
public static mvchtmlstring populatebreadcrumb (string url)
{
StringBuilder str = new StringBuilder ();
list<string> pathList = new list<string> ();
Mvcsitemap current = Getsitemaplist (). FirstOrDefault (M=>m.url==url);
GetParent (current, pathList);
Pathlist.reverse ();
for (int i = 0; i < Pathlist.count; i++)
{
if (i = = pathlist.count-1)
{
string s = pathlist[i];
s = s.substring (S.indexof (">") + 1, s.lastindexof ("<")-S.indexof (">")-1);
Str. AppendFormat ("<li class= ' active ' >{0}</li>", s);
}
Else
{
Str. AppendFormat ("<li>{0}</li>", Pathlist[i]);
}
}
string result = str. ToString ();
return mvchtmlstring.create (Result);
}
Description: First find the current position, recursively find the parent node in order to add to the list; reverse the list and refine the HTML code.
<summary>
Recursion to find the upper level
</summary>
<param name= "Parent" ></param>
<param name= "PathList" ></param>
static void GetParent (Mvcsitemap parent, list<string> pathList)
{
if (parent! = NULL)
{
Pathlist.add (String. Format ("<a href={0}>{1}</a>", parent. URL, parent. Name));
Parent. Parent = Getsitemaplist (). FirstOrDefault (i = i.id = = parent. Parnetid);
GetParent (parent. Parent, pathList);
}
}
Iv. Front-end invocation
Similar to the previous article, we created a new HTML helper for the front-end invocation.
This time we do a little bit of improvement (canonical naming)
Let's take a look at the native HTML helper definition method of Microsoft, taking Html.ActionLink as an example,
As in the box, similar to the name of Xxxextensions, we define a static class to invoke the previous method.
Front-end invocation:
To access Http://localhost/XEngine/home/about as an example, the result of the final return
The corresponding HTML is:
<div>
<br/>
<ol class= "breadcrumb" >
<li><a href=/xengine/> Home </a></li><li><a href=/xengine/organization> organization </a ></li><li class= ' active ' > About </li>
</ol>
</div>
Summarize
This article has made minor improvements to the HTML helper knowledge points used in the previous article:
The custom HTML helper naming is standardized (the class name is Xxxextensions and the native form is unified);
Returns the mvchtmlstring type directly so that the HTML string is not escaped and can be called directly from the front end.
Custom HTML Helper is very useful, you can dig a lot of usage scenarios.
Welcome all comments, wish the study progress:)
P.S.
In the example, the front end is used directly in _layout.cshtml.
Back-end menu-related program structure:
This article from: http://www.cnblogs.com/miro/p/5759585.html
MVC 5 + EF6 Get started complete tutorial 14--Dynamically generate breadcrumb navigation