Search code examples
c#asp.net-mvcasp.net-mvc-4razorhtml.actionlink

ActionLink doesn't generate proper routing url for actions which has two parameters


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


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.