Roy Tinker
Roy Tinker

Reputation: 10152

ASP.NET MVC - Get a URL to the current action that doesn't include the passed ID

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?

Upvotes: 2

Views: 3769

Answers (3)

Chris Shaffer
Chris Shaffer

Reputation: 32585

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.

Upvotes: 1

Chris Shaffer
Chris Shaffer

Reputation: 32585

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.

Upvotes: 0

John Boker
John Boker

Reputation: 83729

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

Upvotes: 0

Related Questions