In ASP.NET MVC how can I use the Razor @Url.Content() helper from C# code?

前端 未结 6 1815
日久生厌
日久生厌 2020-12-03 04:07

I\'m trying to write a html helper extension that outputs an image tag. I need to access (within C# code) something like Razor\'s @Url.Content() helper to get the proper URL

相关标签:
6条回答
  • 2020-12-03 04:43

    Use the following to mimic Url.Content in code.

    VirtualPathUtility.ToAbsolute("~/url/");
    
    0 讨论(0)
  • 2020-12-03 04:43

    You can create your own instance of UrlHelper by passing in the appropriate ViewContext. For example, to do this from an image helper:

    public static string CustomImage(this HtmlHelper html)
    {
        var Url = new UrlHelper(html.ViewContext.RequestContext);
    }
    

    At this point you can call Url.Content() or any other UrlHelper method.

    0 讨论(0)
  • 2020-12-03 04:43

    Yes you can.

    From a controller you can call:

    this.Url.Content("~/Somerelativepath?somethingelse=true");

    0 讨论(0)
  • 2020-12-03 04:52

    You can get to the Request object and thus the URL like this:

    string fullUrl = HttpContext.Current.Request.Url.AbsoluteUri;
    
    0 讨论(0)
  • 2020-12-03 04:53

    Something like this perhaps?

    public static string MyHelper(this HtmlHelper h)
    {
          string url = h.ViewContext.HttpContext.Request.Url.AbsoluteUri;
    }
    
    0 讨论(0)
  • 2020-12-03 04:54

    Yes, use this code to add Url.Content into your code:

    var img_btn_edit = VirtualPathUtility.ToAbsolute("~/Content/images/pencil.png");
    
    0 讨论(0)
提交回复
热议问题