3

I want to have a url link like: /Posts/Post/1#comments

Where: Posts - controller name, Post - action name, 1 - id parameter

I am using following code in my View:

<a href="@Url.Action("Post", "Posts", new { id = @item.PostId + "#comments" })">Comments</a>

As a result I have: /Posts/Post/1%23comments

What to do to pass '#' char instead of "%23"?

Erik Funkenbusch
  • 92,674
  • 28
  • 195
  • 291
angelPL
  • 73
  • 2
  • 11

3 Answers3

3

you're looking for:

<a href="@Url.Action("Post", "Posts", new { id = item.PostId })#comments" ...></a>

# is for hash, so to send it server-side (which Url.Action is expecting) means encoding it. If you're looking to supplement the client experience, don't include it in your Url.Action (or create a special overload that accepts a fragment identifier and outputs it un-touched).

Brad Christie
  • 100,477
  • 16
  • 156
  • 200
1

for that data to be part of the action, %23 is correct; if the # represents a fragment - it isn't part of the "action". A # in a url denotes the client-side fragment - typically used for jumping to an element in a document by id (the server never sees anything after the # in a url)

See also: (look at the url)

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • Yes, but in fact I would like to jump to an element in document... The question is how to do it? – angelPL Dec 05 '14 at 14:31
  • 1
    @user1334190 then: that isn't part of the "action", since the action is server-side, and the server *never sees fragments*; add the `#comments` separately: `href="@(Url.Action(...))#comments"` – Marc Gravell Dec 05 '14 at 14:32
  • href="@(Url.Action(...))#comments" is a simple solution. Thanks! – angelPL Dec 05 '14 at 14:35
0

You can also use Html.ActionLink with proper oveload (fragment parameter) instead of building link manually.

@Html.ActionLink(
           "Comments", 
           "Post", 
           "Posts", null, null, 
           "comments", // fragment part
           new { id = @item.PostId }, 
           new { })
  • For ref [`Html.ActionLink(HtmlHelper,string,string,string,string,string,string,object,object)`](http://msdn.microsoft.com/en-us/library/dd460522(v=vs.118).aspx) & [`Html.ActionLink(HtmlHelper,string,string,string,string,string,string,RouteValueDictionary,IDictionary)`](http://msdn.microsoft.com/en-us/library/dd460522(v=vs.118).aspx). – Brad Christie Dec 05 '14 at 14:42