Umar Farooq Khawaja
Umar Farooq Khawaja

Reputation: 3987

Clarification of ASP.NET MVC routing and model binding

In ASP.NET MVC, I have recently found out that:

This doesn't work and results in an HTTP 404.

public class TestController : Controller
{
    [HttpGet]
    [HttpPost]
    public ActionResult Index(TestModel model)
    {
        return View(model);
    }
}

This works fine.

public class TestController : Controller
{
    public ActionResult Index(TestModel model)
    {
        return View(model);
    }
}

This also works fine:

public class TestController : Controller
{
    [HttpGet]
    [ActionName("Index")]
    public ActionResult GetIndex(TestModel model)
    {
        return View("Index", model);
    }

    [HttpPost]
    [ActionName("Index")]
    public ActionResult PostIndex(TestModel model)
    {
        return View("Index", model);
    }
}

I would like an explanation of why the first version doesn't work, but the other two do work. I would also appreciate if someone could tell me how I can modify the first version to make it work. I like the first version because it is more concise (1 method rather than 2) and also filters out unnecessary HTTP methods.

Upvotes: 0

Views: 107

Answers (1)

Max Toro
Max Toro

Reputation: 28608

HTTP verb attributes are mutually exclusive, a request cannot be both GET and POST at the same time. Instead, you have to do this:

[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
public ActionResult Index(TestModel model) { ... }

Upvotes: 1

Related Questions