开发者

How can I generate url from non-controller static class in asp.net mvc 2 project?

I have created Html help开发者_开发问答er class in asp.net mvc2 project:

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:

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:

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; to the top of your file in order to bring the ActionLink extension method into scope.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜