Michael Edenfield
Michael Edenfield

Reputation: 28338

ASP.NET MVC UrlHelper.Action() not returning correct path

I'm having a problem trying to use the UrlHelper Action() method to point to the /Home/Index action on my site. I need to generate links to Index dynamically (including an id parameter) in client-side script, so I did the obvious:

var url = '@this.Url.Action("Index", "Home")';
function generateLink ( id ) {
  var anchor = "<a href='" + url + "/" + id + "'>Select Me</a>"
  return anchor;
}

But the anchor tags being generated here look like this:

<a href='http://localhost//1013'>Select Me</a>

which obviously doesn't route to the correct action. I'm assuming that Url.Action() is being "smart" by figuring out that Home and Index are the default values for my default route, so http://localhost and http://localhost/Home and http://localhost/Home/Index are functionally identical, but I need to somehow force it to pick the full URL option.

Is there a way to do this, or am I going to have to build the URL up myself?

EDIT:

I haven't change the routing from the defaults for a new MVC3 project:

public static void RegisterRoutes ( RouteCollection routes )
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new
        {
            controller = "Home",
            action = "Index",
            id = UrlParameter.Optional
        } // Parameter defaults
    );
}

ANSWER:

I finally went with a slight variation of @BFree's answer, just because I prefer Html.ActionLink() to Url.Action if I can use it:

var anchor = '@this.Html.ActionLink("Select Me", "Index", "Home", new { id = "XXX" }, null)';

function generateLink ( id ) {
  return anchor.replace("XXX", id);
}

Upvotes: 3

Views: 3112

Answers (2)

BFree
BFree

Reputation: 103742

One hacky approach is to do something like this:

var url = '@this.Url.Action("Index", "Home", new { id = 1})';
function generateLink ( id ) {
  var anchor = "<a href='" + url.replace("1",id) + "'>Select Me</a>"
  return anchor;
}

Upvotes: 2

DanielB
DanielB

Reputation: 20210

A workaround could be:

function generateLink ( id ) {
  var anchor = "<a href='/?id=" + id + "'>Select Me</a>"
  return anchor;
}

Upvotes: 0

Related Questions