从Controller内部使用Html.ActionLink和Url.Action(...)

Pet*_*ron 12 asp.net-mvc html-helper actionlink urlhelper html.actionlink

我想编写一个HtmlHelper来渲染具有预设值的ActionLink,例如.

<%=Html.PageLink("Page 1", "page-slug");%>
Run Code Online (Sandbox Code Playgroud)

where PageLink是一个ActionLink使用已知Action和Controller 调用的函数,例如."索引"和"页面".

由于HtmlHelper并且UrlHelper不存在于Controller类或类中,如何从类中获取动作的相对URL?

更新:鉴于我现在有额外三年积累的经验,这是我的建议:只是使用Html.ActionLink("My Link", new { controller = "Page", slug = "page-slug" })或更好,

<a href="@Url.Action("ViewPage",
                     new {
                           controller = "Page",
                           slug = "my-page-slug" })">My Link</a>
Run Code Online (Sandbox Code Playgroud)

您的扩展方法可能很简单,但它会为招聘添加另一个未经测试的失败点和新的学习要求,而不会增加任何实际价值.将其视为设计复杂系统.为什么要添加另一个移动部件,除非它增加可靠性(否),可读性(很少,一旦你阅读更多文档),速度(无)或并发(无).

jwe*_*ich 20

不确定我是否真的清楚地理解了你的问题,但是,让我试一试.

要创建如您所述的HtmlHelper扩展,请尝试以下操作:

using System;
using System.Web.Mvc;
using System.Web.Mvc.Html;

namespace Something {
    public static class PageLinkHelper
    {
        public static string PageLink(
            this HtmlHelper helper,
            string linkText, string actionName,
            string controllerName, object routeValues,
            object htmlAttributes)
        {
            return helper.ActionLink(
                linkText, actionName, controllerName,
                routeValues, htmlAttributes);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

关于从类中获取URL的问题,取决于您将实现它的类.例如,如果要从HtmlHelper扩展获取当前控制器和操作,可以使用:

string currentControllerName = (string)helper.ViewContext
    .RouteData.Values["controller"];
string currentActionName = (string)helper.ViewContext
    .RouteData.Values["action"];
Run Code Online (Sandbox Code Playgroud)

如果要从控制器获取它,可以使用基类(Controller)中的属性/方法来构建URL.例如:

var url = new UrlHelper(this.ControllerContext.RequestContext);
url.Action(an_action_name, route_values);
Run Code Online (Sandbox Code Playgroud)