4

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> :)

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for pointing out the ", null" parameter, I hadn't noticed it :P
4

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.

4 Comments

I've already tried that, and thought it's not the right way. BEcause when I use what you suggested, I get this url: http://localhost:8231/StoreScreen/AddToCart?Length=9 (StoreScreen instead of StoreCart) and also, how about this Lenght=9 thing? It's the length of the parameter string I pass for the routeValue: "StoreCart"
@Twodordan, oh, that's due to your routing configuration. The ActionLink simply uses your routes.
Sorry, my bad, didn't see the null
@Twodordan, yeah, the null at the end indicates the htmlAttributes parameter. Allows you to pass stuff like @class, etc to this anchor element.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.