【问题标题】:How to pass Area in Url.Action?如何在 Url.Action 中传递区域?
【发布时间】:2015-08-01 04:54:35
【问题描述】:

Html.ActionLink() 中的问题是您不能在它生成的标签内添加额外的 html 内容。 例如,如果您想在文本之外添加一个图标,例如:

<a href="/Admin/Users"><i class="fa fa-users"></i> Go to Users</a>

使用Html.ActionLink(),只能生成:

<a href="/Admin/Users">Go to Users</a>

因此,要解决此问题,您可以使用 Url.Action() 仅生成标签内的 URL,例如:

// Here, Url.Action could not generate the URL "/admin/users". So this doesn't work.
<a href="@Url.Action("", "Users", "Admin")"><i class="fa fa-usesr"></i> Go to Users</a>

// This works, as we know it but won't pass the Area needed.
<a href="@Url.Action("", "Users")"><i class="fa fa-users"></i> Go to Users</a>

那么,如何使用 Url.Action() 传递区域?

【问题讨论】:

  • Url.Action("actionName", "controllerName", new { Area = "areaName" });
  • 根区new { Area = "" }

标签: asp.net-mvc html-helper html.actionlink url.action


【解决方案1】:

你可以使用这个Url.Action("actionName", "controllerName", new { Area = "areaName" });

另外不要忘记添加控制器的命名空间以避免管理区域控制器名称和站点控制器名称之间的冲突。

类似的东西

 public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                "Admin_default",
                "Admin/{controller}/{action}/{id}",
                new { action = "Index", id = UrlParameter.Optional },
                  new[] { "Site.Mvc.Areas.Admin.Controllers" }
            );
        }

【讨论】:

    【解决方案2】:
    @Url.Action("{action}", "{controller}", new { Area = "areaname" });
    @Html.ActionLink("LinkName", "{action}", "{controller}", new { area = "{areaname}" }, new { @class = "btn btn-cool" })
    

    将区域名称写入带有匿名对象的 html 属性。你可以使用 actionlink html helper 扩展方法来实现同样的事情。

    【讨论】:

      【解决方案3】:
      @Url.Action("{action}", "{controller}", new { Area = "areaname" });
      
      @Html.ActionLink("LinkName", "{action}", "{controller}", new { area = "{areaname}"}, new { @class = "btn btn-cool" })
      

      你可以在这个上面使用

      【讨论】:

        【解决方案4】:

        如果你想为根控制器创建链接,使用以下代码就足够了:

        Url.Action("ShowImage", "Page", new { Area = "" })
        

        【讨论】:

          猜你喜欢
          • 2019-08-03
          • 1970-01-01
          • 1970-01-01
          • 2013-04-09
          • 2018-04-04
          • 2015-06-18
          • 1970-01-01
          • 2020-12-29
          • 1970-01-01
          相关资源
          最近更新 更多