How to pass Area in Url.Action?
Asked Answered
M

4

82

The problem in Html.ActionLink() is that you can't add additional html content inside the tag that it generates. For example, if you want to add an icon besides the text like:

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

Using Html.ActionLink(), you can only generate:

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

So, to resolve this, you can use Url.Action() to generate only the URL inside the tag like:

// 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>

So, how do you pass the Area using Url.Action()?

Morentz answered 20/5, 2015 at 5:50 Comment(2)
Url.Action("actionName", "controllerName", new { Area = "areaName" });Narcose
For root area new { Area = "" }Frazzle
S
118

You can use this Url.Action("actionName", "controllerName", new { Area = "areaName" });

Also don't forget to add the namespace of the controller to avoid a conflict between the admin area controller names and the site controller names.

Something like this

 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" }
            );
        }
Sundin answered 20/5, 2015 at 5:59 Comment(0)
C
19
@Url.Action("{action}", "{controller}", new { Area = "areaname" });
@Html.ActionLink("LinkName", "{action}", "{controller}", new { area = "{areaname}" }, new { @class = "btn btn-cool" })

write area name as html attribute with anonymus object. you can use actionlink html helper extension method to achieve same thing.

Cony answered 16/2, 2017 at 6:5 Comment(0)
E
8

If you want to create link for root controllers, it's enough to use this code:

Url.Action("ShowImage", "Page", new { Area = "" })
Ehrenberg answered 31/7, 2021 at 5:30 Comment(0)
K
3
@Url.Action("{action}", "{controller}", new { Area = "areaname" });

@Html.ActionLink("LinkName", "{action}", "{controller}", new { area = "{areaname}"}, new { @class = "btn btn-cool" })

You can use above this

Knowing answered 6/2, 2020 at 9:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.