HttpGet and HttpPost in MVC


HttpGet and HttpPost Attribute

HttpGet and HttpPost both are the attributes used in asp.net mvc application. We use both attributes on action represents the http requests like whether it is get request or post request.
Before understanding the HttpGet and HttpPost attributes let’s understand the following problem:-
We have created following MVC Application to Sum two numbers.

  
<form method="post" action="">
    <table>
        <tr>
            <td> Enter First Number</td>
            <td> <input type="text" id="i1" name="n1" /></td>
        </tr>
        <tr>
            <td>
                Enter Second Number
            </td>
            <td>
                <input type="text" id="i2" name="n2" />
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" value="Sum" />
            </td>
        </tr>
    </table>
</form>    

Therefore, if we create Action for the same example we need two actions to complete this task. First Action will open the page and Second Action will perfume the sum action in the following manner:-
  
  public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult Index(int n1, int n2)
        {
            int z = n1 + n2;
            Response.Write("The sum is " + z);
            return View();
        }
}

  
  
In this code, first Index action is used to open the UI Page and Second Index Action is used to submit the request.
Now if we executes this page it will show the following error:-
  
  httpget and httppost error
  Figure 2
  
  
Therefore, to solve this ambiguity error we will use HttpGet and HttpPost attributes in the following manner
  
  [HttpGet]
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Index(int n1, int n2)
        {
            int z = n1 + n2;
            Response.Write("The sum is " + z);
            return View();
        }

  
  
As we know when application first called it would be Get Request so it will call First Index method and when we submit the form, it would be post request so it will call Second Index method, which is decorated as HttpPost Attribute.
Now Executes the Code and you will get following output:-


No comments:

Post a Comment