如何通过区域在 Url。行动? ?

在 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 ()传递 Area 呢?

83277 次浏览

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" }
);
}
@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.

@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

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

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