URL Encode string for Href ASP.NET MVC / Razor

前端 未结 4 981
长发绾君心
长发绾君心 2020-12-16 12:34

I\'m trying to build an Href using Razor The string is going to end up looking like this:

https://www.notmysite/controller/action?order_ID=xxxxxxx&hashComparator

相关标签:
4条回答
  • 2020-12-16 12:44

    I've figured out a way of doing it:

    @{
      var url = string.Format(
          "https://www.notmysite.co.uk/controller/action?order_ID={0}&hashComparator={1}",
          @Uri.EscapeDataString(Model.bookingNumber.ToString()),
          @Uri.EscapeDataString(Model.hashCode));
    }
     <p><a href="@url">Click Here to be transferred</a></p>
    

    Edit 2015 - As mentioned by Jerads post - The solution is to only encode the query string elements and not the whole URL - which is what the above does.

    0 讨论(0)
  • 2020-12-16 12:49

    The easier method is to use @Html.Raw(Model.SomethingUrl)

    0 讨论(0)
  • 2020-12-16 12:59

    The problem is that you're trying to encode the whole URL. The only pieces you want to encode are the querystring values, and you can just use Url.Encode() for this.

    You don't want to encode the address, the querystring params, or the ? and & delimiters, otherwise you'll end up with an address the browser can't parse.

    Ultimately, it would look something like this:

    <a href="https://www.notmysite.co.uk/controller/action?order_ID=@Url.Encode(Model.bookingNumber)&hashComparator=@Url.Encode(Model.hashCode)">Click Here to be transferred</a>
    
    0 讨论(0)
  • 2020-12-16 13:02

    This was the first link that came up for this issue for me. The answers didn't work for me though because I am using core, I think. So wanted to add this in.

    System.Net.WebUtility.UrlEncode(MyVariableName)
    

    If Url.Encode doesn't work try the above. Also as stated before don't use this on the entire URL string, just use it for the individual querystring variables. Otherwise there is a good chance your URL wont work.

    0 讨论(0)
提交回复
热议问题