在ASP.NET MVC中根据用户参数更改breadcrumb

本文关键字:参数 用户 breadcrumb ASP NET MVC | 更新日期: 2023-09-27 18:04:01

我使用MvcSiteMapProvider将面包屑添加到我的网站。我想根据ActionResult中使用的参数更改breadcrumb跟踪。因此,链接如下所示:localhost:49345/Evaluation/ChoicePeriod?typeControl=Input

SiteMapPath的当前视图:Main > Evaluation

预期视图:Main > Evaluation > Input

路线:

  routes.MapRoute(
            name: "Evaluation",
            url: "Evaluation/ChoicePeriod/{action}/{typeControl}",
            defaults: new { action = "Index", typeControl = UrlParameter.Optional }
        );
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Main", action = "Index", id = UrlParameter.Optional }
        );

网站地图:

<mvcSiteMapNode title="Main" controller="Main" action="Index">
 <mvcSiteMapNode title="Evaluation" area="Evaluation" controller="ChoicePeriod" action="Index" >
  <mvcSiteMapNode title="Input" area="Evaluation" controller="ChoicePeriod" action="Index" preservedRouteParameters="typeControl" key="typeControl"/>
 </mvcSiteMapNode>
</mvcSiteMapNode>

我已经将typeControl值添加到RouteValues中,现在我不知道如何在SiteMapPath 中显示它

    public ActionResult Index(string typeControl, int? id_pred)
    {
        var node = MvcSiteMapProvider.SiteMaps.Current.FindSiteMapNodeFromKey("typeControl");
        if (node != null)
        {
            node.RouteValues["typeControl"] = typeControl;
        }
        ...

有没有办法让我的面包屑看起来像我期望的那样?谢谢

在ASP.NET MVC中根据用户参数更改breadcrumb

typeControl=""参数添加到Evaluation节点,以在其具有值时强制不匹配。

<mvcSiteMapNode title="Main" controller="Main" action="Index">
 <mvcSiteMapNode title="Evaluation" area="Evaluation" controller="ChoicePeriod" action="Index" typeControl="">
  <mvcSiteMapNode title="Input" area="Evaluation" controller="ChoicePeriod" action="Index" preservedRouteParameters="typeControl" key="typeControl"/>
 </mvcSiteMapNode>
</mvcSiteMapNode>

此外,您应该更新路由,使其生成与其匹配的相同URL,并提供controller RouteValue,因为MVC需要它。

routes.MapRoute(
    name: "Evaluation",
    url: "Evaluation/ChoicePeriod",
    defaults: new { controller = "ChoicePeriod", action = "Index" }
);

使用MvcBreadCrumbs,您可以在控制器中添加这样的代码:

public class SampleController : Controller
{
    [BreadCrumb]
    public ActionResult GetProduct(int id)
    {
        var model = db.GetProduct(id);
        BreadCrumb.SetLabel("Product " + model.ProductName);
        return View(model);
    }
}

然后在View.cshtml上显示如下:

@Html.Raw(BreadCrumb.Display())

您应该在mvc.sitemap:中使用URL

<mvcSiteMapNode title="Main" controller="Main" action="Index">
 <mvcSiteMapNode title="Evaluation" area="Evaluation" controller="ChoicePeriod" action="Index" >
  <mvcSiteMapNode title="Input" area="Evaluation" controller="ChoicePeriod" action="Index" url="/Evaluation/ChoicePeriod/Input"/>
 </mvcSiteMapNode>
</mvcSiteMapNode>