How to use MVC 3 @Html.ActionLink inside c# code

前端 未结 5 1031
庸人自扰
庸人自扰 2021-01-17 09:59

I want to call the @Html.ActionLink method inside a c# function to return a string with a link on it.

Something like this:

string a = \"Email is lock         


        
5条回答
  •  别那么骄傲
    2021-01-17 10:21

    You could create an HtmlHelper extension method:

    public static string GetUnlockText(this HtmlHelper helper)
    {
        string a = "Email is locked, click " + helper.ActionLink("here to unlock.", "unlock");
        return a;
    }
    

    or if you mean to generate this link outside of the scope of an aspx page you'll need to create a reference to an HtmlHelper and then generate. I do this in a UrlUtility static class (I know, people hate static classes and the word Utility, but try to focus). Overload as necessary:

    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);
    }
    

    Then you can write the following from wherever your heart desires:

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

提交回复
热议问题