ASP.NET MVC - HTML 扩展方法构建 URL 或链接
考虑一个扩展方法,其目的是:
- 在某些条件下呈现
标记
- ,仅返回不带链接的字符串
问题:在扩展方法中,如何利用路由值等正确的路由逻辑,而不是对字符串进行硬编码。我怀疑 HtmlHelper.GenerateRouteLink 是解决方案的一部分,但请建议实现此目的的最佳方法。
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
}
更多信息:
- 使用 ASP.NET MVC 1.0
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我昨天只需要做类似的事情。可能有一种更巧妙的方法来做到这一点,但它可以帮助我准确地了解正在发生的事情,所以我不做任何假设。
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.
这行得通吗?
would this work?
我对GenerateRouteLink 的体验是一场艰苦的战斗。自从我搞乱它以来已经有一段时间了,但如果这是我想到的方法,微软已将其设置为“内部”,因此您无法在 MVC 程序集之外访问和使用它。有很多我尝试过但并不真正喜欢的解决方法。
为了避免在辅助方法中对 url 进行硬编码,我最终所做的就是让它接受“字符串 url”参数,并在调用辅助方法时在我的视图中使用 Url.Action。这不是最干净的,但它是一种对我来说效果很好的解决方法。
My experience with GenerateRouteLink has been an uphill battle. It's been a while since I messed with it but if it's the Method I'm thinking of Microsoft has made it "internal" so you can't access and use it outside the MVC assembly. There are a number of workarounds that I played with and didn't really like.
What I ended up doing to avoid hard coding the url in my helper methods is have it accept a 'string url' parameter and use Url.Action in my view when I call the helper method. It's not the cleanest but it's a workaround that worked well for me.