Wednesday, 16 March 2016

What is [HttpPost] and [HttpGet] attributes in MVC?

There are  many Http attributes are there in MVC. These all works like method attribute of form element.

<form action="/login" method="post">   
    <input type="text" name="userName" placeholder="Enter user name">
 <input type="text" name="password" placeholder="Enter password">
    <input type="submit" value="Login">
</form>


Inheritance Hierarchy

System.Object
  System.Attribute
    System.Web.Mvc.ActionMethodSelectorAttribute
      System.Web.Mvc.AcceptVerbsAttribute
      System.Web.Mvc.HttpDeleteAttribute
      System.Web.Mvc.HttpGetAttribute
      System.Web.Mvc.HttpHeadAttribute
      System.Web.Mvc.HttpOptionsAttribute
      System.Web.Mvc.HttpPatchAttribute
      System.Web.Mvc.HttpPostAttribute
      System.Web.Mvc.HttpPutAttribute
      System.Web.Mvc.NonActionAttribute

[HttpGet]
public ActionResult Login() {
    return View();
}

[HttpPost]
public ActionResult Login(string userName, string password) {
    // do login stuff
    return View();
}


HttpGet explanation

GET - Requests data from a specified resource
An hyperlink or anchor tag that points to an action will ALWAYS be an HttpGet.
Data is submitted as a part of url.
Data is visible to the user as it posts as query string.
It is not secure but fast and quick.
It use Stack method for passing form variable.
Data is limited to max length of query string.
It is good when you want user to bookmark page.


HttpPost explanation

POST - Submits data to be processed to a specified resource
A Submit button will always initiate an HttpPost request.
Data is submitted in http request body.
Data is not visible in the url.
It is more secured but slower as compared to GET.
It use heap method for passing form variable
It can post unlimited form variables.
It is advisable for sending critical data which should not visible to users.