如何在C#代码中使用MVC 3 @Html.ActionLink

16

我想在C#函数中调用@Html.ActionLink方法,以返回一个带有链接的字符串。

就像这样:

string a = "Email is locked, click " + @Html.ActionLink("here to unlock.", "unlock") ;

我想要做的是添加一个带有链接的“ModelState.AddModelError”来解决错误。 - roncansan
5个回答

8
假设您想在控制器中完成此操作,需要跨越几个障碍。您必须实例化一个 ViewDataDictionary 和一个 TempDataDictionary。然后需要使用 ControllerContext 创建一个 IView。最后,您可以使用所有这些元素(加上您的 RouteCollection),创建您的 HtmlHelper

完成以上步骤后,您可以使用 LinkExtensions.ActionLink 创建自定义链接。在视图中,您需要使用 @Html.Raw() 显示您的链接,以防止它们被 HTML 编码。以下是必要的代码:
var vdd = new ViewDataDictionary();
var tdd = new TempDataDictionary();
var controllerContext = this.ControllerContext;
var view = new RazorView(controllerContext, "/", "/", false, null);
var html = new HtmlHelper(new ViewContext(controllerContext, view, vdd, tdd, new StringWriter()),
     new ViewDataContainer(vdd), RouteTable.Routes);
var a = "Email is locked, click " + LinkExtensions.ActionLink(html, "here to unlock.", "unlock", "controller").ToString();

展示完所有内容后,我要提醒您最好在视图中完成这个操作。将错误和其他信息添加到您的ViewModel中,然后编写视图以创建链接。如果需要在多个视图中使用此功能,请创建一个HtmlHelper来创建链接。
更新:
针对one.beat.consumer的问题,我的初始答案是一个示例,说明了可能的解决方法。如果开发人员需要重复使用此技术,则可以将其复杂性隐藏在静态帮助程序中,如下所示:
public static class ControllerHtml
{
    // this class from internal TemplateHelpers class in System.Web.Mvc namespace
    private class ViewDataContainer : IViewDataContainer
    {
        public ViewDataContainer(ViewDataDictionary viewData)
        {
            ViewData = viewData;
        }

        public ViewDataDictionary ViewData { get; set; }
    }

    private static HtmlHelper htmlHelper;

    public static HtmlHelper Html(Controller controller)
    {
        if (htmlHelper == null)
        {
            var vdd = new ViewDataDictionary();
            var tdd = new TempDataDictionary();
            var controllerContext = controller.ControllerContext;
            var view = new RazorView(controllerContext, "/", "/", false, null);
            htmlHelper = new HtmlHelper(new ViewContext(controllerContext, view, vdd, tdd, new StringWriter()),
                 new ViewDataContainer(vdd), RouteTable.Routes);
        }
        return htmlHelper;
    }

    public static HtmlHelper Html(Controller controller, object model)
    {
        if (htmlHelper == null || htmlHelper.ViewData.Model == null || !htmlHelper.ViewData.Model.Equals(model))
        {
            var vdd = new ViewDataDictionary();
            vdd.Model = model;
            var tdd = new TempDataDictionary();
            var controllerContext = controller.ControllerContext;
            var view = new RazorView(controllerContext, "/", "/", false, null);
            htmlHelper = new HtmlHelper(new ViewContext(controllerContext, view, vdd, tdd, new StringWriter()),
                 new ViewDataContainer(vdd), RouteTable.Routes);
        }
        return htmlHelper;
    }
}

然后,在控制器中,可以这样使用它:
var a = "Email is locked, click " + 
    ControllerHtml.Html(this).ActionLink("here to unlock.", "unlock", "controller").ToString();

或者像这样:
var model = new MyModel();
var text = ControllerHtml.Html(this, model).EditorForModel();

虽然使用 Url.Action 更加容易,但现在它已经扩展成为一个强大的工具,在控制器中使用所有 HtmlHelpers(具有完整的智能提示)生成任何标记。

可以使用该工具生成带有模型和编辑器模板的标记,用于电子邮件、PDF 生成、在线文档传递等多种用途。


counsellorben,@roncansan...请看一下我修改后的答案。我认为这完全是不必要的。 - one.beat.consumer
1
一个完整的解决方案和良好编写的代码。我并不是在批评它;我只是认为控制器不是“生成标记”的合适位置。也许有点过于纯粹,但控制器的作用是处理路由调用,收集必要的资源(模型、服务)并将它们注入视图中。视图的主要目的是对模型进行模板化。我认为控制器不应该用于表示层功能,除非没有其他选择。你能想到需要在控制器中保留标记的情况吗? - one.beat.consumer
你能想到一种需要在控制器中保留标记的场景吗?比如包含指向其他资源的链接的本地化验证消息,例如“发生错误,请单击{0}以修复此问题。”不过,@tvanfosson的答案可能更有道理。 - trevorc
我没有看到 new ViewDataDictionary(vdd) 的构造函数。看起来它可以是任何实现 IViewDataContainer 接口的类,但 .NET 中是否有一个实现它的类呢?如果您想要构建一个简单的类,可以自己构建:class ViewDataContainer : IViewDataContainer { public ViewDataDictionary ViewData { get; set; } } - KyleMit

6

这些其他答案有几个问题...

Shark的回答需要你将LinkExtensions命名空间引入到C#中,这并不是错的,但对我来说不太理想。

Hunter创建一个辅助程序的想法更好,但为单个URL编写辅助函数仍然很麻烦。你可以编写一个辅助程序来帮助你构建接受参数的字符串,或者你可以用传统的方式解决:

var link = "Email is... click, <a href=\"" + Url.Action("action") + "\"> to unlock.</a>";

@counsellorben,

我认为这个问题并不复杂;用户只需要将Action的路由渲染成包含锚点标签的硬字符串。此外,在硬编码的拼接字符串中使用ActionLink()是没有意义的,并且强制开发人员使用本应用于视图的LinkExtensions。

如果用户一定要使用ActionLink(),或者由于某种原因不需要在构造函数中计算该字符串,则在视图中进行计算会更好。

我仍然坚持并推荐tvanfosson和我提供的答案。


6
您可以创建一个HtmlHelper扩展方法:
public static string GetUnlockText(this HtmlHelper helper)
{
    string a = "Email is locked, click " + helper.ActionLink("here to unlock.", "unlock");
    return a;
}

如果您想在 aspx 页面之外生成此链接,则需要创建对 HtmlHelper 的引用,然后生成链接。我在一个静态类 UrlUtility 中实现了这个功能(我知道,人们不喜欢静态类和“Utility”这个单词,但请专注于主题)。根据需要进行重载:

public static string ActionLink(string linkText, string actionName, string controllerName)
{
    var httpContext = new HttpContextWrapper(System.Web.HttpContext.Current);
    var requestContext = new RequestContext(httpContext, new RouteData());
    var urlHelper = new UrlHelper(requestContext);

    return urlHelper.ActionLink(linkText, actionName, controllerName, null);
}

然后你可以在心仪的位置编写以下内容:
string a = "Email is locked, click " + UrlUtility.ActionLink("here to unlock.", "unlock", "controller");

1
这应该是被采纳的答案……因为其他答案不允许在模型中生成您的链接…… - Serj Sagan

4

最好的方法是在控制器中使用UrlHelper手动构建链接。话虽如此,我怀疑在视图或部分视图中可能有更好的处理方式,无论是共享的还是其他方式。

string a = "Email is locked, click <a href=\""
              + Url.Action( "unlock" )
              + "\">here to unlock.</a>";

1

或许试试这个:

string a = "Email is locked, click " + System.Web.Mvc.Html.LinkExtensions.ActionLink("here to unlock.", "unlock");

3
如果我这样调用ActionLink函数,我需要传递三个参数,第一个应该是(this HtmlHelper htmlHelper)类型的,第二个是linkText,第三个是controller。关于第一个参数,我尝试了null和创建一个新的HtmlHelper,但都没有成功。 - roncansan
此扩展方法需要 HtmlHelper 实例。 - Reza

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接