Coder Social home page Coder Social logo

zhaytam / smartbreadcrumbs Goto Github PK

View Code? Open in Web Editor NEW
159.0 9.0 76.0 746 KB

A utility library for ASP.NET Core (both MVC and Razor Pages) websites to easily add and customize breadcrumbs.

Home Page: https://blog.zhaytam.com/2018/06/24/asp-net-core-using-smartbreadcrumbs/

License: MIT License

C# 100.00%
asp-net-core breadcrumbs utility-library bootstrap smartbreadcrumbs customize-breadcrumbs razor-pages asp-net-core-mvc

smartbreadcrumbs's Introduction

SmartBreadcrumbs 2.0.0

A utility library for ASP.NET Core (both MVC and Razor Pages) websites to easily add and customize breadcrumbs.

About the 2.0.0 version

When I created SmartBreadcrumbs, it only worked on MVC websites.
Razor Pages then came out and became "more popular", so I rewrote the whole code base, cleaned the project's structure, wrote unit tests and now, SmartBreadcrumbs works on both MVC and Razor Pages websites, even on the same project.
If you're interested in the README of the old version, it's available here: OLD_README.

Informations

Badges
Build Build Status Azure DevOps tests
NuGet NuGet Nuget
License GitHub

Documentation & Example

  • Wiki: A list of all the possible things you can do with SmartBreadcrumbs.
  • RazorPagesAndMvc: An example project containing both MVC and Razor Pages pages. Check it out to see how SmartBreadcrumbs works.

Usage

Install

Install the package using NuGet
Install-Package SmartBreadcrumbs

Initialize

After you have setup your breadcrumbs (using the Breadcrumb and DefaultBreadcrumb attributes), go ahead and add SmartBreadcrumbs in your services:

services.AddBreadcrumbs(GetType().Assembly);

Use

SmartBreadcrumbs comes with a breadcrumb tag that renders the breadcrumbs for you, to use it:

  1. In _ViewImports.cshtml, add @addTagHelper *, SmartBreadcrumbs.
  2. In your _Layout.cshml (or specific pages), use <breadcrumb></breadcrumb>.

Customize

Options

You can specify options when you initialize SmartBreadcrumbs:

services.AddBreadcrumbs(GetType().Assembly, options =>
{
	options.TagName = "nav";
	options.TagClasses = "";
	options.OlClasses = "breadcrumb";
	options.LiClasses = "breadcrumb-item";
	options.ActiveLiClasses = "breadcrumb-item active";
	options.SeparatorElement = "<li class=\"separator\">/</li>";
});

More

Check out the documentation if you need more customization!

  • You can manually create and set breadcrumb nodes, useful when you have dynamic breadcrumbs (e.g. E-Commerce website).
  • You can get access to the BreadcrumbManager and create your own TagHelper for example.

Credits & License

Credits: zHaytam and the contributors.
License: SmartBreadcrumbs is open source, licensed under the MIT License.

smartbreadcrumbs's People

Contributors

ahmedatia avatar askalione avatar connerorth avatar icesasoftcorp avatar jmuronis avatar julianyus avatar kharabet avatar ksummerlin avatar lukaszdobrzynski avatar maxpiva avatar oleksandrnechaiev avatar sethsteenken avatar shmulyeng avatar zhaytam avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

smartbreadcrumbs's Issues

Add Option to IconClasses

Hi there!

It would be awesome to also include in the BreadCrumbAttribute the property:

        public virtual string IconClasses { get; set; } 

Example:

        [Breadcrumb("ViewData.Title", CacheTitle = true, IconClasses="fa fa-edit")]
        public async Task<IActionResult> Index()
        {
            var svc_result = await _service.GetProductList();
            return View(svc_result);
        }

To be able to use it on
BreadcrumbOptions.LiTemplate and BreadcrumbOptions.ActiveLiTemplate
at Startup -> ConfigureServices

Example:

            services.UseBreadcrumbs(GetType().Assembly, options =>
            {
                options.TagName = "";
                options.TagClasses = "";
                options.OlClasses = "breadcrumb";
                options.LiClasses = "";
                options.ActiveLiClasses = "active";
                options.LiTemplate = "<li><a href=\"{1}\"><i class=\"{2}\"></i>{0}</a></li>";
                options.ActiveLiTemplate = "<li class=\"active\"><a href=\"{1}\"><i class=\"{2}\"></i>{0}</a></li>";
            });

Thank you!

Sequence contains no matching element

I am getting error as 'Sequence contains no matching element'

I am working on .net core 2.2 application and i had set DefaultBreadcrumb in my HomeController and Breadcrumb attribute in remaining Controllers action methods but on startup.cs in services.AddBreadcrumbs(GetType().Assembly) line getting error as Sequence contains no matching element.

Can anyone facing similar issue ?can anyone guide regarding same.

Breadcrumbs display only in <li> elements?

I installed the NuGet package as directed in the Wiki article. The breacrumbs are displaying on my views as list elements:

  1. Home
  2. Contact Us
  3. Support
  4. Knowledge Base

I would like them to display like this:

Home > Contact Us > Support > Knowledge Base

There is no explanation about how to do this that I can find. Can you help? Is this set up in options?

Thanks!

Most recent version breaks breadcrumb rendering...

I updated my project from using 3.4.0 to 3.5.0 (that being the only change I performed). Everything compiles fine... however I get the following runtime error that throws an error:

image

Not sure what you changed in the last update, but something is awry.

How to name different Breadcrumb when having same action method and same controller

Hi ,
I have question arises now how can i provide different Breadcrumb node name having same action method but with different input parameter.

here is my code
public async Task<IActionResult> Index(bool Modal=false) { if (Modal==true) { return View("Modal"); // this will have link as [Breadcrumb("ModalTrue")] } else return View(config); // this will have link as [Breadcrumb("ModalFalse")] }

how can i achieve above?

More than one DefaultBreadcrumb or option to hide it

Hello,
Is it possible to add more than one DefaultBreadcrumb or hide it with some option? I'm in a scenario where the application has 4 modules for different user groups (departments). A "Home" option is not very feasible since once you access the system in your specific module, it will hardly change the module because you would not have permissions to do so. Ideally each module would have its "Home"

XSS

Hello,

I've noticed that string passed to the constructor MvcBreadcrumNode don't prevent xss attacks.
(Maybe because they're not escaped before rendering)

My workaround is to encapsulate my string with HttpUtility.HtmlEncode(string) but it's a tedious process.
Is there a workaround built-in your library?

Thank you very much

The escaped version:
image

Without workaround:
image
image

Make library as netstandard, not netcoreapp

Hi @zHaytam ,

When i tried to use your package in my class library, I've got an error:
error NU1202: Package SmartBreadcrumbs 1.0.3.3 is not compatible with netstandard2.0 (.NETSt andard,Version=v2.0). Package SmartBreadcrumbs 1.0.3.3 supports: netcoreapp2.0 (.NETCoreApp,Version=v2.0)

So I found the solution. (According this issue). You should make it as netstandard that anyone can use it in all their projects. Not only in web project.

Thank you

BreadcrumbAttribute&DefaultBreadcrumbAttribute Areas in RouteValues

There is an option to add additional feature to BreadcrumbAttribute and DefaultBreadcrumbAttribute
For example whe you have structure like:
Areas -> Home -> Controllers, Views, Models
Under your blog post there are comment, i had the same requirement
I will do PR for it

V2 - No docs about manual nodes

So I made the possible mistake up upgrading to the new version which has caused all of my manual BreadcrumbNode creations to fail with an error about being unable to create an instance of an abstract class or interface.

Is there a document on how to upgrade from your old version to this newer version? I looked through the readme and the wiki to no avail.

ActionResult actions aren't considered

` public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
var child = await output.GetChildContentAsync();

        string nodeKey = GetNodeKey(ViewContext.ActionDescriptor.RouteValues);

        var node = ViewContext.ViewData["BreadcrumbNode"] as BreadcrumbNode ?? _breadcrumbManager.GetNode(nodeKey);

        output.TagName = BreadcrumbManager.Options.TagName;

        // Tag Classes
        if (!string.IsNullOrEmpty(BreadcrumbManager.Options.TagClasses))
        {
            output.Attributes.Add("class", BreadcrumbManager.Options.TagClasses);
        }

        output.Content.AppendHtml($"<ol class=\"{BreadcrumbManager.Options.OlClasses}\">");

        var sb = new StringBuilder();

        // Go down the hierarchy
        if (node != null)
        {
            if (node.OverwriteTitleOnExactMatch && node.Title.StartsWith("ViewData."))
                node.Title = ExtractTitle(node.OriginalTitle);

            sb.Insert(0, GetLi(node, node.GetUrl(_urlHelper), true));

            while (node.Parent != null)
            {
                node = node.Parent;

                // Separator
                if (BreadcrumbManager.Options.HasSeparatorElement)
                {
                    sb.Insert(0, BreadcrumbManager.Options.SeparatorElement);
                }

                sb.Insert(0, GetLi(node, node.GetUrl(_urlHelper), false));
            }
        }

        // If the node was custom and it had no defaultnode
        if (!BreadcrumbManager.Options.DontLookForDefaultNode && node != _breadcrumbManager.DefaultNode)
        {
            // Separator
            if (BreadcrumbManager.Options.HasSeparatorElement)
            {
                sb.Insert(0, BreadcrumbManager.Options.SeparatorElement);
            }

            sb.Insert(0, GetLi(_breadcrumbManager.DefaultNode,
                _breadcrumbManager.DefaultNode.GetUrl(_urlHelper),
                false));
        }

        output.Content.AppendHtml(sb.ToString());
        output.Content.AppendHtml(child);
        output.Content.AppendHtml("</ol>");
    }`

At line 47 in the var node, when the action is an async he will always return a null, still tryng to find why, but probably some await missing.

Support for Razor Pages

Would be good if this was working with project that uses Razor pages only.
Reason being that Microsoft is recommending RP as the preferred approach.

From Create a web app with ASP.NET Core MVC

We recommend you try the Razor Pages tutorial before the MVC/Controller/Views version. The Razor Pages tutorial:
Is the preferred approach for new application development.
Is easier to follow.
Covers more features.

Solved: Support for Razor Class Library (also how to use Razor Pages in Areas)

Because reflection is used to parse all the breadcrumb attributes, if you use controllers or razor pages in Razor Class Library (outside your application's assembly), you need a way to pass its assembly to the SmartBreadcrumbs constructor.

Added additional methods to ServiceCollectionExtensions.cs:

public static void AddBreadcrumbs(this IServiceCollection services, Assembly[] assembly)
{
AddBreadcrumbs(services, assembly, new BreadcrumbOptions());
}

    public static void AddBreadcrumbs(this IServiceCollection services, Assembly[] assembly, Action<BreadcrumbOptions> optionsSetter)
    {
        var options = new BreadcrumbOptions();
        optionsSetter.Invoke(options);
        AddBreadcrumbs(services, assembly, options);
    }

    private static void AddBreadcrumbs(IServiceCollection services, Assembly[] assembly, BreadcrumbOptions options)
    {
        var bm = new BreadcrumbManager(options);
        foreach(Assembly a in assembly)
        {
            bm.Initialize(a);
        }
        
        services.AddSingleton(bm);

        services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();
    }

Then, just created an assembly array in Startup.cs:
Assembly[] assemblies = new Assembly[] { GetType().Assembly, typeof(MyApp.Models.BrandConfig).Assembly };
services.AddBreadcrumbs(assemblies, options =>
{
options.TagName = "nav";
options.TagClasses = "";
options.OlClasses = "breadcrumb";
options.LiClasses = "breadcrumb-item";
options.ActiveLiClasses = "breadcrumb-item active";
options.SeparatorElement = "<li class="separator"> > ";
options.DontLookForDefaultNode = true;
});

(MyApp.Models.BrandConfig is just a static class in the razor class library - you can pick any class in your library).

Also, had trouble getting this to work with Razor Pages nested in areas. Some of the posts indicate this does not work with areas, but was able to get it to work by specifying the AreaName in the attribute. Example used in scaffolding Core 3.1 Identity pages:

using SmartBreadcrumbs.Attributes;

namespace MyApp.Areas.Identity.Pages.Account.Manage
{
[Breadcrumb("Email", FromPage = typeof(IndexModel), AreaName = "Identity")]
public partial class EmailModel : PageModel { ...

InvalidOperationException: Sequence contains no matching element

Hello,

I have a run-time error while starting the app with SmartBreadcrumbs.
The error points to the Startup File:
image
The startupfile looks exactly like is descriped:
image
The Default Node has been set. Other than that there are not yet other nodes set.

Does anyone know the cause of this problem?

Razor Pages - Passing Ids into breadcrumb so links work actions

Hi,

I have been attempting to implement your breadcrumbing solution into a Razor page - based solution. Any pages where no route-params are required works great. However, when we pass asp-route- between pages I cannot for the life of me work out how to implement your solution.

I read that you can manually create child nodes:

var childNode3 = new RazorPageBreadcrumbNode("/Path", "ViewData.Something")
{
	OverwriteTitleOnExactMatch = true,
	Parent = childNode2
};

// Tell SmartBreadcrumbs to use them;
// PS: Use the last created node.
ViewData["BreadcrumbNode"] = childNode3;

However, this clears the entire breadcrumb route I had previously and I still cannot get the Ids to pass through so the page either doesn't redirect and/or gets caught in missing id error handling.

Is it possible to get some sort of explanation or example such that I could implement breadcrumbing as below:
https://i.gyazo.com/36b40fd7fd9c842a2b0b428c2d6244e7.png

Where the breadcrumbs could be passed one or more Ids? e.g. Forms page, select a form -> formVersion page, select a formVersion -> you then have two pages that require working link breadcrumbs, one requiring a formId, one requiring both a formId and formVersionId, etc

Kind regards,
Matt

manually configure BreadcrumbNode gives exception in the service

Hello,

I dont seem to get the manually node configuration to work. The annotation method works except for the action taking a parameter which is lost on clicking the breadcrumb.
The manual node does not have a DefaultNode as parent. I upgraded to 1.4 but without succes.

I tried:

//[Breadcrumb(“ViewData.Title”, CacheTitle = true, FromAction = “Interaction.Index”)]
public IActionResult Edit(Guid id)
{

var parentNode = new BreadcrumbNode(“InteractionIndex”, “Index”, “Interaction”, id, null);
var editInteractionNode = new BreadcrumbNode(“ViewData.Title”, “Edit”, “Interaction”, id, parentNode);

The id is the routevalue i need to pass.

I get an exception in services saying “Sequence contains no matching element

i have this one in HomeController

[DefaultBreadcrumb(“Home”, CacheTitle = true)]
public IActionResult Index()
{
return View();
}

The Edit action in Interaction controller is in Home > Admin > Interaction > Edit

We use a LocalizedTaghelper derived from the original Taghelper, basically a copy paste of some functions and adding localization on the strings. This worked until i tried configuring a manual node.
I also noted that some of the examples on this didnt match the number and order of prameters in the src. I followed source and could compile, running gives the exception.

Kind regards,
Martien

BreadcrumbAttribute should only be allowed on methods and classes

(Default)BreadcrumbAttribute have no effect when placed on anything besides methods or classes.
Make this apparent by added AttributeTargets restrictions such as:
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]

Provide an easier way to set aria-label

In order to be compliant with the WCAG guidelines, one should set a aria-label to the breadcrumb navigation, if there are more than one

element on the page. This is the case on most pages.

There is a workaround by appying the aria-label to the TagName of the BreadcrumbOptions like this:

o.TagName = "nav aria-label=\"Some description of the navigation\"";

An appropriate property would be a better way to handle this and should be fairly easy to implement.

Async operations with ValueTask

Does the library support async operations with ValueTasks?
For example the following code does not work but if i change the ValueTask to Task it is working fine
[Breadcrumb("Cars")] public async ValueTask<IActionResult> Index() { var carTypes = await PopulateVesselTypesDropDownAsync(); ViewData["carTypes "] = carTypes ; return View(); }

How to Create several levels of Nodes

Background:
I have pages in the main area of the application (/Pages/Index.cshtml, /Pages/Categories/xx.cshtml, /Pages/Products/xx.cshtml)
and I have pages in 2 areas (/Area1/Pages/xx, and /Area2/Pages/xxx)

I would like the bread crumbs in the areas to be like Home (root)/Home1 (area1 root)/xxx.cshtml

Is this possible and how?

SmartBreadCrumbsException - No Node Exists

Hi,
I am trying to implement Breadcrumbs into a small MVC App with a single controller. However, I keep getting the exception "No Node Exists the has ReviewApplication as a Key"

Even though I have Breadcrumbs setup for this Action e.g.

[Breadcrumb("ReviewApplication", FromAction = "Apply_Step4")
public async Task ReviewApplication() { ... }

[Breadcrumb("EditApplication", FromAction = "ReviewApplication")
public async Task EditApplication() { ... }

DefaultBreadcrumb on Controller throws InvalidOperationException

Create default project, add [DefaultBreadcrumb] to any Controller.
Run project.
See "Sequence contains no matching element" exception message.

Stacktrace:

  Name Value Type
  StackTrace " at System.Linq.Enumerable.Single[TSource](IEnumerable1 source, Func2 predicate)\r\n at SmartBreadcrumbs.BreadcrumbManager.GenerateHierarchy(Dictionary`2 entries) in \SmartBreadcrumbs\src\BreadcrumbManager.cs:line 67\r\n at SmartBreadcrumbs.BreadcrumbManager.Initialize(Assembly assembly) in SmartBreadcrumbs\src\BreadcrumbManager.cs:line 55\r\n at SmartBreadcrumbs.Extensions.ServiceCollectionExtensions.AddBreadcrumbs(IServiceCollection services, Assembly assembly, BreadcrumbOptions options) in \SmartBreadcrumbs\src\Extensions\ServiceCollectionExtensions.cs:line 27\r\n at SmartBreadcrumbs.Extensions.ServiceCollectionExtensions.AddBreadcrumbs(IServiceCollection services, Assembly assembly) in

I think this error is being thrown because the BreadcrumbManager.Initialize method.
Does not consider attributes on controller class only on controller methods.

My suggestion would be to also check for BreadcrumbAttribute on controller class level just like with razor page model class level.

How can use Smartbreadcrumbs in blazor

I tried to use like this

namespace BreadcrumbSample.Data
{

[Breadcrumb]
public class WeatherForecastService
{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };
    [DefaultBreadcrumb("My Home")]
    public Task<WeatherForecast[]> GetForecastAsync(DateTime startDate)
    {
        var rng = new Random();
        return Task.FromResult(Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = startDate.AddDays(index),
            TemperatureC = rng.Next(-20, 55),
            Summary = Summaries[rng.Next(Summaries.Length)]
        }).ToArray());
    }
    [Breadcrumb("About us")]
    public string AboutUs()
    {
        // In this case, the DefaultNode will be the parent of this node.
        return "About";
    }
 


    [Breadcrumb("Contact us", FromAction = "WeatherForecastService.AboutUs")]
    public string ContactUs()
    {
        // This page is a child of the About us page
        return "";
    }

}

}
//In my stratup file
services.AddBreadcrumbs(GetType().Assembly, options =>
{
// Testing
options.DontLookForDefaultNode = true;
});

But i get noting

Index breadcrumb always shows, even if user did not access that page

My DefaultBreadcrumb is "Home". So let's say on my MVC home page, the user can navigate to two different links.

<a href="/Contact/Index">Index</a>
<a href="/Contact/Edit?contactId=##">Edit</a>

One goes to controller/action Contact/Index and one goes to Contact/Edit. I have a breadcrumb attribute for both in the ContactController. When the user navigates to Contact/Index, the breadcrumbs correctly looks like:

Home / Index

When the user navigates to Contact/Edit, the breadcrumbs incorrectly looks like:

Home / Index / Edit

The user should not be able to navigate back to Index on this breadcrumb, only to Home.
It should look like this:

Home / Edit

Is this a bug?

Thanks!
Bryan

Unable to add breadcrumb attribute for Razor page with same page name in an Area

I have a razor page in the main part of the application [/Pages/Index.cshtml]
I also have an area named StyleGuide which has an index page in the root [/Area/StyleGuide/Pages/Index.cshtml]
When I launch the solution an error is thrown in the

The error is thrown in the StartUp.cs in the ConfigureServices method at the services.AddBreadcrumbs(GetType().Assembly) call.
The error is: An item with the same key has already been added. Key: /Index

ArgumentException When Decorating Action Overload(s)

If an MVC controller has two Add() action overloads, one decorated with [HttpGet] and the other with [HttpPost], the following exception is thrown.

System.ArgumentException: An item with the same key has already been added. Key: Forms.Add
at System.Collections.Generic.Dictionary.TryInsert(TKey key, TValue value, InsertionBehavior behavior)
at SmartBreadcrumbs.BreadcrumbManager.Initialize(Assembly assembly)
at SmartBreadcrumbs.Extensions.ServiceCollectionExtensions.AddBreadcrumbs(IServiceCollection services, Assembly assembly, BreadcrumbOptions options)

It seems to behave correctly only having decorated the [HttpGet] action with [Breadcrumb]. Could this scenario be added to the documentation, or could keys be distinguished by the action method signature? I didn't try with multiple [HttpGet] overloads.

Breadcrumb blank when page is in a subfolder

Our razor pages web application is starting to grow so we added subfolders to the Pages directory. So far everything seems to be rendering fine but we're having issues with the last breadcrumb showing blank.

Pages
-> Clients
----> Index.html
Index.html

Actions with the same name in different areas

Is there any way to debug a key duplicity error?
I changed the entire system structure to use areas and now there are some controllers with the same name. I try to run the debug but the maximum I get is the duplicate key (Home.Index), but I do not know how to solve it.
Thanks.

Area Support - Generating non-area parent urls incorrectly includes the area value of the current page

Generating a parent url for an action or controller that is not part of an Area while on a page that is part of an Area causes the parent urls to assume the Area of the current page. This is because IUrlHelper.Action will use the current page's area route value when generating the url even if null is supplied as the RouteValues parameter.

string GetUrl(IUrlHelper urlHelper) => urlHelper.Action(Action, Controller, RouteValues);

When RouteValues above is null (AreaName not specified on BreadcrumbAttribute), the route value area on the current page is supplied when generating the url.

Looks like node url generating logic needs to explicitly include an empty area in the route values for nodes that do not specify an area. Something like this on BreadcrumbNode constructor:

Current:

if (!string.IsNullOrWhiteSpace(areaName))
{
	RouteValues = new
	{
		area = areaName
	};
}

New:

RouteValues = new
{
	area = areaName?.Trim() ?? string.Empty
};

This way, for controllers and actions that are not under an Area, the route values will explicitly say { area = string.Empty } so the url helper will generate the url properly. What do you think? My preliminary testing checks out. I'd be glad to make a pull request for this, but wanted to run it by someone else. Thanks!

Multiple inheritance of Controller

Found some small issues, please take a look at screenshot bellow.
My controllers are a bit complex.

public abstract class BaseController : Controller
public abstract class ViewController : BaseController
public class HomeController : ViewController

The same issue might happen with return types (IActionResult, Task<IActionResult>) It can be JsonResult for example or some CustomResult.

untitled111

Thanks for your little component which does a huge job. Regards.

Incompatibility with net461

Hi zHaytam,

I am having an issue with using SmartBreadcrumbs, i can't install the NuGet package because my project has Target Framework 4.6.1 which is newer than netcoreapp2.0.
Will this be supported in the near future and do you have an estimate for it? Or is there a workaround that i could try?

Unfortunately i cannot change the TargetFramework version because of the other projects in the solution and their dependencies.

Thanks in advance,
Alex

Issue with Manual nodes

Trying to create manual nodes like below but somehow both nodes are pointing to Post1 action: /Java/Advanced/Post1

Advance node should point to /Java/Advanced/Index but it's not.
Am I doing something wrong ?

namespace RazorPagesAndMvc.Controllers.Java
{
    [Route("Java/Advanced/[action]")]
    public class AdvancedJavaController : Controller
    {
        [HttpGet]
        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        [Breadcrumb("Advanced", FromAction = "Index", FromController = typeof(JavaController))]
        public IActionResult Index(int i)
        {
            return View();
        }

        [HttpGet]
        public IActionResult Post1()
        {
            var childNode1 = new MvcBreadcrumbNode("Index", "Advanced", "Advance")
            {
                OverwriteTitleOnExactMatch = false,
            };

            var childNode2 = new MvcBreadcrumbNode("Post1", "Advanced", "Post1")
            {
                OverwriteTitleOnExactMatch = false,
                Parent = childNode1
            };

            ViewData["BreadcrumbNode"] = childNode2;
            return View();
        }

    }
}

Startup options not working in 1.0.4.1

We were using version 1.0.3.3 and liking it. We upgraded to version 1.0.4.1 recently, but the options defined in ConfigureServices are no longer working at all. Specifically 'options.ActiveLiClasses = "breadcrumb-item active";' didn't work anymore, the class was not being added in our razor views.

On most Actions we simply use '[Breadcrumb("ViewData.Title", CacheTitle = true, FromController = nameof(DashboardController), FromAction = nameof(DashboardController.Index))]', but this resulted in the actual text "ViewData.Title" being rendered in the page.
Downgrading to 1.0.3.3 resolved both issues.

On a sidenote: In the https://github.com/zHaytam/SmartBreadcrumbs#options section, the part "options." is missing for each of the 6 lines.

SmartBreadcrumbs does not work with MVC area

I have a MVC .net core Web Application. I have a HomeController in the root controller folder. I also have a EmployersController in the Employer folder under the areas. When I click on Add Employer, it will put the breadcrumb correctly like "Home/Add Employer" with the URL (http://localhost:49932/Employer/Employers/AddEmployer) . However, when I click on Home to go back to home, it took me to http://localhost:49932/Employer, which I guess to be the home of that area. Is it possible to let it take me to http://localhost:49932/, which is the index URL for HomeController?

Passing parameters to action when manually creating nodes

Hi!

First, thanks for your amazing work!

Second, I just updated to the 2.0.0 version and I can't seem to find how to pass parameters to my actions justlike we did in the previous version:

var childNode1 = new BreadcrumbNode("Action 1", "Home", "Action1", null, new { id = 10 });

Thank you,

Victor

An unhandled exception occurred while processing the request. ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index

I keep running into this issue:

An unhandled exception occurred while processing the request.
ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

I've only set up one breadcrumb which is the home, here's the code:

        [DefaultBreadcrumb("Home")]
        public async Task<IActionResult> Index()
        {
            var user = await _userService.GetByEmailAsync(User.Identity.Name, x => x.Oysters);
            return View(user);
        }

Any help on this? I'm using v1.4

SmartBreadcrumbsException: The full name Web.CreateModel doesn't contain 'Pages'

I'm using v3.1.1 of SmartBreadcrumbs.

Getting this error message:

SmartBreadcrumbsException: The full name Web.CreateModel doesn't contain 'Pages'.
SmartBreadcrumbs.Extensions.ReflectionExtensions.ExtractRazorPageKey(Type pageType)

The error gets thrown when the Startup code runs for adding breadcrumbs:

services.AddBreadcrumbs(GetType().Assembly, options =>
{
    options.OlClasses = "breadcrumb hidden-print";
});

I have a Razor page model which inherits an abstract type for implementing a user creation wizard:

    [Breadcrumb("User")]
    public class CreateModel : WizardPageModel<UserWizardTransaction, IUserProcessor>
    {
        public CreateModel(IWizardService<UserWizardTransaction> wizardService, IUserProcessor processor) 
            : base(wizardService, processor)
        {
            
        }

        public override ActionResult Redirect(int? entityId)
        {
            return RedirectToAction("Detail", new { id = entityId })
                .SuccessToast($"User {MessageHandler.CreationSuccess}");
        }
    }

An excerpt from my abstract Razor Page model which exists in my Web.Models namespace:

    public abstract class WizardPageModel<TWizardTransaction, TProcessor> : PageModel
        where TWizardTransaction : WizardTransaction
        where TProcessor : ITransactionProcessor
    {
        [BindProperty]
        public TWizardTransaction WizardTransaction { get; set; }

        public TProcessor Processor { get; set; }

        protected IWizardService<TWizardTransaction> WizardService { get; set; }

        public abstract ActionResult Redirect(int? entityId);

        protected WizardPageModel(IWizardService<TWizardTransaction> wizardService, TProcessor processor)
        {
            WizardService = wizardService;
            Processor = processor;
        }

        public IActionResult OnGet(Guid? transactionId, int? step)
        {
            WizardTransaction = WizardService.GetTransactions(transactionId, step);
            return Page();
        }

        public IActionResult OnPost()
        {
            var action = WizardTransaction.IsFinalStep() ? WizardAction.Finish : WizardAction.Next;
            return Save(action);
        }

        public IActionResult OnPostSave()
        {
            return Save(WizardAction.Save);
        }
    }

Any thoughts on why this might be throwing an exception? On a normal Razor page, adding the breadcrumb attribute works correctly.

e.g.

  [Breadcrumb("Settings")]
   public class IndexModel : PageModel
   {
       private readonly DataContext _dataContext;

       public SystemSettings SystemSettings { get; set; }

       public IndexModel(DataContext dataContext)
       {
           _dataContext = dataContext;
       }

       public void OnGet()
       {
           SystemSettings = _dataContext.Settings.Result;
       }

       public IActionResult OnPost()
       {
           if (ModelState.IsValid)
           {
               return RedirectToPage("Index").SuccessToast("Settings updated");
           }

           return Page();
       }
   }

Therefore, I'd have to assume the problem is something to do with my user create wizard inheriting the abstract WizardPageModel type?

Error stack trace:

SmartBreadcrumbs.SmartBreadcrumbsException: The full name Web.CreateModel doesn't contain 'Pages'.
at SmartBreadcrumbs.Extensions.ReflectionExtensions.ExtractRazorPageKey(Type pageType)
at SmartBreadcrumbs.BreadcrumbManager.HasBreadcrumb(Type type, BreadcrumbNodeEntry& entry)
at SmartBreadcrumbs.BreadcrumbManager.Initialize(Assembly assembly)
at SmartBreadcrumbs.Extensions.ServiceCollectionExtensions.AddBreadcrumbs(IServiceCollection services, Assembly assembly, BreadcrumbOptions options)
at SmartBreadcrumbs.Extensions.ServiceCollectionExtensions.AddBreadcrumbs(IServiceCollection services, Assembly assembly, Action`1 optionsSetter)
at Web.Startup.ConfigureServices(IServiceCollection services) in C:\Git\EcomFrameworkCore\Web\Startup.cs:line 114
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.InvokeCore(Object instance, IServiceCollection services)
at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.<>c__DisplayClass9_0.g__Startup|0(IServiceCollection serviceCollection)
at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.Invoke(Object instance, IServiceCollection services)
at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.<>c__DisplayClass8_0.b__0(IServiceCollection services)
at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.UseStartup(Type startupType, HostBuilderContext context, IServiceCollection services)
at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.<>c__DisplayClass12_0.b__0(HostBuilderContext context, IServiceCollection services)
at Microsoft.Extensions.Hosting.HostBuilder.CreateServiceProvider()
at Microsoft.Extensions.Hosting.HostBuilder.Build()
at Web.Program.Main(String[] args) in C:\Git\EcomFrameworkCore\Web\Program.cs:line 11

Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.