質問

I have created Html helper 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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top