How to pass special character via url in ASP.NET MVC?

3.8k Views Asked by At

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

There are 3 best solutions below

3
On BEST ANSWER

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

3
On

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)

1
On

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 { })