Dave K.
Dave K.

Reputation: 258

How to create a url for a view that has a variable passed into it?

I've looked into this on my own and I'm currently not having any luck. I read Microsoft's documentation on routes and I've tried to implement it but I don't quite understand how it works. I tried working it out but all of the routes I tried are giving me the same error, so currently I am still using the Default route in RouteConfig.cs.

For my Controller I have a class that takes in a int

public ActionResult ViewGame(int id)

In my .cshtml file for it I have a list of games, with their names being Html.ActionLink to take the user to the correct page when you click on the link.

@Html.ActionLink(game.title, "ViewGame", "Game", new { id = game.id })

When I am selecting the link it is sending me to url like this:

http://localhost:58858/Home/ViewGame?Length=4

The error on the page reads:

Server Error in '/' Application.

The resource cannot be found.

Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.

Requested URL: /Home/ViewGame

I'm unsure how to fix this error and what I need to do to make

Upvotes: 0

Views: 42

Answers (1)

Shyju
Shyju

Reputation: 218742

You are using the method overload wrong

There is another overload of ActionLink helper which lets you specify the controller name, action name and the route values.

public static MvcHtmlString ActionLink(
    this HtmlHelper htmlHelper,
    string linkText,
    string actionName,
    string controllerName,
    object routeValues,
    object htmlAttributes
)

This should work

@Html.ActionLink(game.title, "ViewGame", "Game", new { id = game.id },null)

Upvotes: 1

Related Questions