[英]How can I generate url from non-controller static class in asp.net mvc 2 project?
I have created Html helper class in asp.net mvc2 project: 我在asp.net mvc2项目中创建了HTML帮助器类:
public static class CaptionExtensions
{
public static string Captions(this HtmlHelper helper, Captions captions)
{
var sb = new StringBuilder();
sb.AppendLine("<ul>");
foreach (var caption in captions)
{
// var url = Url.Action("CaptionCategory", new {id = caption.Code} )
sb.AppendLine("<li>");
sb.AppendLine( "<a href="+ url + ">");
sb.AppendLine( caption);
sb.AppendLine( "</a>");
sb.AppendLine("</li>");
}
sb.AppendLine("</ul>");
return sb.ToString();
}
}
I need to generate url similar with the way in commented line. 我需要生成与注释行中的方式类似的网址。 Commented code is how I do it in the controller class, but this is helper class (static context). 注释的代码是我在控制器类中的工作方式,但这是辅助类(静态上下文)。 Any help??? 有帮助吗???
Simply create an UrlHelper out of the RequestContext property of the HtmlHelper and use it to generate urls: 只需从HtmlHelper的RequestContext属性中创建一个UrlHelper并使用它来生成url:
var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
var url = urlHelper.Action("CaptionCategory", new { id = caption.Code });
or in your particular case use the html helper to generate the anchor instead of hardcoding it as you did: 或者在您的特定情况下,使用html helper生成锚,而不是像您那样对其进行硬编码:
sb.AppendLine("<li>");
sb.AppendLine(
helper.ActionLink(
caption,
"CaptionCategory",
new { id = caption.Code }
).ToHtmlString()
);
sb.AppendLine("</li>");
For this to work you should obviously add using System.Web.Mvc.Html;
为此,您显然应该using System.Web.Mvc.Html;
添加using System.Web.Mvc.Html;
to the top of your file in order to bring the ActionLink
extension method into scope. 到文件顶部,以便将ActionLink
扩展方法纳入范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.