asp.net-mvc – URL of route being assembled incorrectly

Question:

I'm with a project in asp.net mvc 4, using AttributeRouting to assemble the routes, and I'm seeing some strange behavior.

By mounting my GET and POST actions in this order:

    [GET("editar/{id}")]
    public ActionResult Editar(int id)
    {
        return View();
    }

    [POST("salvar-edicao")]
    public ActionResult Editar(string teste)
    {
        return View();
    }

The address of my form is as follows:

<form action="/editar/1" method="post"> <input type="submit" value="Enviar">

Causing it not to post to the correct location, returning me 404. However, if I reverse the order of the two methods, putting POST first, the form address is assembled correctly, but the link to call get is not :

    [POST]
    public ActionResult Editar(string teste)
    {
        return View();
    }

    [GET("editar/{id?}")]
    public ActionResult Editar(int id)
    {
        return View();
    }

form:

<form action="/Editar" method="post">

link:

@Html.ActionLink("Teste", "Editar", "Home", new { id = 1 }, new { })

mounted like this

http://localhost/Editar?id=1 instead http://localhost/Editar/1

Can someone help me?

Answer:

Apparently for the form to be posted correctly using attributeouting, the methods must have identical routes.

[POST("editar/{id}")]
public ActionResult Editar(Pessoa teste)
{
    return View();
}

[GET("editar/{id}")]
public ActionResult Editar(int id)
{
    return View();
}

That way the links and forms are assembled and respond correctly.

Scroll to Top