Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC - HTML Extension method building a URL or link

Consider an extension method whose purpose is to either:

  • render an <a> tag
  • on some condition, just return a string without a link

  Question: in an extension method, how can you leverage the proper routing logic with Route Values, etc. rather than hardcoding the string. I suspect HtmlHelper.GenerateRouteLink is part of the solution, but please suggest the best way to achieve this.

public static string CreateUserLink(this HtmlHelper html, string userAcctName)
{
    if (string.IsNullOrEmpty(userAcctName))
        return "--Blank--";

    //some lookup to A.D.            
    DomainUser user = ADLookup.GetUserByAcctName(userAcctName);

    if (user == null)
        return userAcctName;

    //would like to do this correctly!
    return string.Format("<a href='/MyAppName/User/View/{0}' title='{2}'>{1}</a>"
                        , user.Mnemonic, user.DisplayName, user.Location);

    //normally returns http://mysite.net/MyAppName/User/View/FOO
    }

More info:

  • using ASP.NET MVC 1.0

alt text

like image 222
p.campbell Avatar asked Dec 30 '22 06:12

p.campbell


1 Answers

I just had to do something similar to this yesterday. There may be a slicker way to do it, but it helps me to see exactly what is going on, so I don't assume anything.

public static string CreateUserLink(this HtmlHelper html, string userAcctName)
{
    if (string.IsNullOrEmpty(userAcctName))
        return "--Blank--";

    //some lookup to A.D.            
    DomainUser user = ADLookup.GetUserByAcctName(userAcctName);

    if (user == null)
        return userAcctName;

    RouteValueDictionary routeValues = new RouteValueDictionary();

    routeValues.Add("controller", "User");
    routeValues.Add("action", "View");
    routeValues.Add("id", user.Mnemonic);

    UrlHelper urlHelper = new UrlHelper(html.ViewContext.RequestContext);
    TagBuilder linkTag = new TagBuilder("a");

    linkTag.MergeAttribute("href", urlHelper.RouteUrl(routeValues));
    linkTag.MergeAttribute("title", user.Location);
    linkTag.InnerHtml = user.DisplayName;

    return linkTag.ToString(TagRenderMode.Normal);
}
like image 176
Neil T. Avatar answered Jan 22 '23 03:01

Neil T.