Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GET and POST to same Controller Action in ASP.NET MVC

I'd like to have a single action respond to both Gets as well as Posts. I tried the following

[HttpGet] [HttpPost] public ActionResult SignIn() 

That didn't seem to work. Any suggestions ?

like image 560
Cranialsurge Avatar asked Jul 12 '10 20:07

Cranialsurge


People also ask

Can we have two action methods with same name in MVC?

While ASP.NET MVC will allow you to have two actions with the same name, . NET won't allow you to have two methods with the same signature - i.e. the same name and parameters. You will need to name the methods differently use the ActionName attribute to tell ASP.NET MVC that they're actually the same action.

What is GET and POST action types in MVC?

Both GET and POST method is used to transfer data from client to server in HTTP protocol but the Main difference between the POST and GET method is that GET carries request parameter appended in URL string while POST carries request parameter in message body which makes it more secure way of transferring data from ...

What is HttpGet and HttpPost in MVC?

HttpGet and HttpPost are both the methods of posting client data or form data to the server. HTTP is a HyperText Transfer Protocol that is designed to send and receive the data between client and server using web pages.

Can one action method have multiple views?

Yes, completely possible. And, it can be multiple views, or even a FileResult or other result type.


2 Answers

This is possible using the AcceptVerbs attribute. Its a bit more verbose but more flexible.

[AcceptVerbs(HttpVerbs.Get|HttpVerbs.Post)] public ActionResult SignIn() { } 

More on msdn.

like image 181
Ryan Bair Avatar answered Sep 20 '22 08:09

Ryan Bair


Actions respond to both GETs and POSTs by default, so you don't have to specify anything:

public ActionResult SignIn() {     //how'd we get here?     string method = HttpContext.Request.HttpMethod;     return View(); } 

Depending on your need you could still perform different logic depending on the HttpMethod by operating on the HttpContext.Request.HttpMethod value.

like image 30
Kurt Schindler Avatar answered Sep 18 '22 08:09

Kurt Schindler