Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Sitemap Provider -- Maintaining URL parameters in breadcrumb trail

I'm using the MvcSiteMapProvider from http://mvcsitemap.codeplex.com/ to create a breadcrumb trail for my project. I have some URLs that need an ID to be passed to present information for the appropriate user, e.g. http: //localhost:52306/Home/User?ID=101101

When I navigate further into the sitemap (e.g. http: //localhost:52306/Home/User/Details?ID=101101) and try to use the breadcrumb link to take me back to the "User" page, the ID parameter is lost. I have tried adding SiteMapPreserveRouteData attributes to the action methods, but they don't seem to be doing anything. Is there an easy way to make sure this ID information is preserved? I thought the SiteMapPreserveRouteDataAttribute was supposed to do this, so is there something I am doing wrong with the attribute? My method would look like this:

[SiteMapPreserveRouteData]
public ActionResult User()
{
  //code
}

Let me know if you need any more info from me.

like image 712
Ben Avatar asked Jun 16 '11 14:06

Ben


1 Answers

The way I did it, I took original mvc site map helper source for rendering breadcrumb, and changed it to handle parameters (although in my project we display only parameters for filtering and allow user to click on them to loose other filtering parameters, below is very naive implementation of node text, just an example how it can be done):

   private static string SiteMapText(this MvcSiteMapHtmlHelper helper, SiteMapNode node, string linkCssClass, IDictionary<string, object> htmlAttributes)
    {
        var extraAttributes = new StringBuilder();
        foreach (var attribute in htmlAttributes)
        {
            extraAttributes.Append(" " + attribute.Key + "=\"" + attribute.Value + "\"");
        }            

        string spanHtml;
        var paramDictionary = helper.HtmlHelper.ViewContext.RequestContext.HttpContext.Request.Params.ToDictionary();
        var queryParams = paramDictionary.Select(x => string.Format("{0}:{1}", x.Key, x.Value));

        // here you add request parameters
        var title = helper.HtmlHelper.Encode(string.Format("{0} ({1})", node.Title, string.Join(";", queryParams)));

        if (!string.IsNullOrEmpty(linkCssClass))
        {
            spanHtml = string.Format("<span><span class=\"{0}\"{1}>{2}</span>", linkCssClass, extraAttributes, title);
        }
        else
        {
            spanHtml = string.Format("<span><span{1}>{0}</span>", title, extraAttributes);
        }

        return spanHtml;
    }

In the same way you can adjust SiteMapLink methods, to include request parameters for current node.

like image 84
Giedrius Avatar answered Sep 19 '22 11:09

Giedrius