Question

In the view

@Html.ActionLink("Edit", "Edit", new { id = 1, year = 1 }) 

In the controller

// GET: /Forecasts/Edit/5
public ActionResult Edit(int id, short year)
{
    ...
}

It generated a url like

http://<localhost>/controllername/actionname/1?year=1

I would expect the actionlink generate a URL like : http://<localhost>/controllername/actionname/?id=1&year=1

This url cannot be interpreted by MVC default routing, why the URL is not generated in the expected way? Thanks.

Update: Now I found out it was a typo caused this problem for me, but the answer below is still good enough as it help me to further understand the way route works

Was it helpful?

Solution

You are using the default route, which will be formatted like this:

"{controller}/{action}/{id}"

Which means the first parameter will be id and will be written just after the /, without any named GET parameter.

If you want to have explicit parameters everywhere, just use this route configuration:

"{controller}/{action}"

If you remove the id all your parameters will be named.

OTHER TIPS

I would expect the actionlink generate a URL like : http://<localhost>/controllername/actionname/?id=1&year=1

You cannot expect something like this if you are using the default route:

routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

Get rid of the {id} from the if you expect such url pattern:

routes.MapRoute(
    "Default",
    "{controller}/{action}",
    new { controller = "Home", action = "Index" }
);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top