asp.net-mvc 如何在 Url.Action 中传递区域?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30341268/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-07 23:27:20  来源:igfitidea点击:

How to pass Area in Url.Action?

asp.net-mvchtml-helperhtml.actionlinkurl.action

提问by doncadavona

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:

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

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

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

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

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

因此,要解决此问题,您可以使用 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>

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

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

回答by sakir

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

你可以用这个 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" }
            );
        }

回答by Hardik

@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.

使用匿名对象将区域名称写为 html 属性。您可以使用 actionlink html helper 扩展方法来实现相同的目标。

回答by Sam pandya

@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

你可以在这个上面使用