Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET: ActionLink return relative url

I'm new to working on MVC2 asp.net projects.

I was wondering, is it possible to have an action link like this:

<%: Html.ActionLink("[Add To Cart]", "../StoreCart/AddToCart", new { id = Model.id })%>

Note the ../StoreCart.

Here's a returned URL example (I am currently in StoreScreen when I see the ActionLink, but I would like to get out, "one level up" so to speak):

Bad (404): http://localhost:8231/StoreScreen/StoreCart/AddToCart?id=9

Desired: http://localhost:8231/StoreCart/AddToCart?id=9

Thanks!

PS: Why can't you just do a php like thing and write a custom <a href="<%: index + "/StoreCart/AddToCart?id=" + id %>" > add to cart </a> :)

like image 480
Spectraljump Avatar asked Dec 27 '22 20:12

Spectraljump


2 Answers

The ActionLink is not intended to point to a physical URL, rather a action in a controller.

<%: Html.ActionLink("[Add To Cart]", "AddToCart", "StoreCart", new { id = Model.id }, null)%>

Note: The final null is needed as this override of the ActionLink requires it. It is the model, and can be an object or null.

Docs

like image 185
Dustin Laine Avatar answered Jan 02 '23 00:01

Dustin Laine


You shouldn't be passing ../StoreCart/AddToCart as argument to an ActionLink. The second argument of an ActionLink is the action name and I highly doubt that your action is called ../StoreCart/AddToCart.

So what you want is (which would use the same controller as the current request url):

<%: Html.ActionLink("[Add To Cart]", "AddToCart", new { id = Model.id }) %>

and if you wanted to set a specific controller just use the proper overload:

<%: Html.ActionLink(
     "[Add To Cart]", 
     "AddToCart", 
     "StoreCart", 
     new { id = Model.id }, 
     null
) %>

And here's a list of all available overloads I would recommend you checking out.

like image 29
Darin Dimitrov Avatar answered Jan 02 '23 00:01

Darin Dimitrov