0

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

anIBMer
  • 1,159
  • 2
  • 12
  • 20

2 Answers2

5

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" }
);
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • thank you mate, the same answer as as @ppetrov, he responded earlier though. It is a pity that i can not mark both as answers, don't know why. – anIBMer May 15 '13 at 23:40
5

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.

ppetrov
  • 3,077
  • 2
  • 15
  • 27