Christian
Christian

Reputation: 117

Use Get And Post in the same Controller

I want to use the HttpGet and HttpPost attributes for one action method. However, I have only seen examples where the attributes are used individually on separate action methods.

For example:

public ActionResult Index()
    {
        //Code...
        return View();
    }

    [HttpPost]
    public ActionResult Index(FormCollection form)
    {
        //Code...
        return View();
    }

I want to have something like this:

[HttpGet][HttpPost]
public ActionResult Index(FormCollection form)
{
    //Code...
    return View();
}

I remember having seen this done somewhere, but cannot remember where.

Upvotes: 1

Views: 668

Answers (1)

Daniel J.G.
Daniel J.G.

Reputation: 34992

If you really want to do that, you can use the [AcceptVerbs] attribute. (See this SO question)

This way your method can handle the GET and POST verbs (but not others like PUT)

[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
public ActionResult Index(FormCollection form)
{
    //Code...
    return View();
}

If you want your method to handle all verbs, don´t use any attribute at all:

public ActionResult Index(FormCollection form)
{
    //Code...
    return View();
}

Upvotes: 3

Related Questions