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"?

3 Answers 3

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).

Sign up to request clarification or add additional context in comments.

3 Comments

That's the answer for my question. Thanks!
Technically: "fragment identifier", not hash
@MarcGravell: Tomäto Tomâto. I guess I group it given the JavaScript API labels it "hash" (even though its a hash + fragment). But I've re-worded it. ;-)
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)

3 Comments

Yes, but in fact I would like to jump to an element in document... The question is how to do it?
@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"
href="@(Url.Action(...))#comments" is a simple solution. Thanks!
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 { })

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.