Consider an extension method whose purpose is to either:
<a>
tag
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:
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With