views:

504

answers:

3

I have an action in which I want to intercept any possible integer id that comes and place it behind a hash. (I have some Javascript that is handling the id). I am only doing this extra step for the sake of URL-hackers like me who might forget my convention of putting a hash before the id.

Here is my action:

public ActionResult Edit(int? id)
{
    if (id != null) return Redirect(Url.Action("Edit") + "/#" + id);

    return View();
}

The problem is that the Url.Action method is preserving the passed id. Url.Action("Edit") is returning "{controller}/Edit/{id}". I want it to just return "{controller}/Edit"! (And my code is tacking on an additional "/#{id}").

For example, a request to this URL:

http://localhost:2471/Events/Edit/22

is redirecting to this URL:

http://localhost:2471/Events/Edit/22/#22

when I want it to redirect to this URL:

http://localhost:2471/Events/Edit/#22

I'm frustrated. Does anyone know how to get a URL to the current action that doesn't include the passed id?

A: 

I'm not completely sure but could you use the RedirectToAction method ?

http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.redirecttoaction.aspx

John Boker
See my comments for Chris Shaffer's answer -- it's URL-encoding the "#".
Roy Tinker
A: 

I'm not 100% sure (and don't have my dev machine to test), but I think you could pass the hash within the id parameter and it would work...eg:

Url.Action("Edit", "Events", new { id = "#" + id });

or you could use RedirectToAction() the same way.

An alternative would be to define a Route {controller}/{Action}/#{id} and then use Url.Route() instead.

Chris Shaffer
Hmm, close, but it's URL-encoding the "#". So the redirect goes to /Events/Edit/%2322
Roy Tinker
I also tried defining a route to {controller}/{action}/#{id} but it's URL-encoding the "#" again.
Roy Tinker
D'oh, didn't think about the URL Encoding. I suppose my last suggestion would be defining a route that does not include the id at all that you could concatenate with; eg Route "{controller}/{Action}/", then tack on the "#id" as you already are.
Chris Shaffer
Yeah, that works. Thank you. Edit your answer and I'll accept it.
Roy Tinker
I added a new answer instead - figured that way this conversation wouldn't be hanging around making no sense, plus people can see a way NOT to do it :)
Chris Shaffer
+1  A: 

One way to do this would be to define a route for the controller action, eg the Route would be defined as "{controller}/{action}/". Then use something similar to the following to build your actual URL:

Url.RouteUrl("MyRoute") + "#" + id

Not the best method, but it works. Maybe someday Microsoft will add fragment support to routing.

Chris Shaffer