Get current fragment in Route, ASP.net MVC

2019-01-26 19:32发布

问题:

Is there away to get the current fragment from a route that was issued via action link. This is how I am getting the action from the route.

string currentAction = requestContext.RouteData.Values["action"] as string ?? "index";

Can I do something similar to this?

string currentFragment = requestContext.RouteData.Values["Fragment"] as string ?? "";

回答1:

No, you can't do anything like this. The fragment (everything that follows the # sign in an url) is never sent to the server by the browser, so the sole fact of talking about getting the url fragment server side simply doesn't make sense.

So if you have the following url: http://example.com/foo/bar?key1=value1#abc the server will never be able to fetch abc simply because the client will never send it.



回答2:

As it has already been pointed out that is not possible. Document fragments (the string after the hash as you call it) are intended for the browsers only to correctly position the viewport. They have no meaning for the server and therefore are not transmitted there.

There is however a workaround you can use. Repeat the fragment as part of your url to make it accessible for the server.

Look at the permalink to the answers in this question. For instance, the link to my answer looks like this:

http://stackoverflow.com/questions
/6285833/get-current-fragment-in-route-asp-net-mvc/6286097#6286097

See how the value 6286097 is duplicated as the last route parameter. It's intentional. You can use this technique as well.

P.S. The fragment must point to an identifier in the document (id of some HTML element). At least in XHTML only identifiers work as fragments. Valid ids may not begin with a digit therefore instead of #6286097 use something like #answer-6286097.

P.S.#2. Do not use any JavaScript trickery to get around this limitation. Basic site functionality and design must work without JavaScript - don't listen to anyone who tells you otherwise. Fragments obviously belong to the basic tool box. Use JavaScript only for advanced interactivity.