Search code examples
c#asp.netasp.net-mvchttp-postactionmethod

mvc 3 - Automatically going to HttpPost


I have an action as follows:

    public ActionResult ChangeFeeCheck(string id)
    {

       ViewBag.id = id;
       return View();
    }

on my View, I have the following:

    @{
      ViewBag.Title = "CreateList";
     }



     Please enter first name <br /><br />


    @using (Html.BeginForm())
    {

    @Html.Textbox("firstname")

    <input type="button" id="SaveChanges" value="Save" />  
    }    

When I click on the button, I was expecting it to to the following

    [HttpPost]
public ActionResult ChangeFeeCheck(string firstname)
    {
      .....

    }

I am not sure when MVC will automatically go to the HttpPost or if I when need to manually have it there. In the above, it does not go there directly. I have to use the

    window.location.href

and pass the url of the controller/action.

Meaning, isn't the default for

    Html.BeginForm()

The HttpPost(same name as the HttpGet)


Solution

  • If you are following "Convention over configuration" rule over here, then the view you have created here must be for ChangeFeeCheck action, and ChangeFeeCheck here looks like will make compiler confused as no overload, same name, same signatures.

    and then when method for form is get it would go to the first one, while if method for form is POST, it will call the one decorated with [HttpPost]

    And because you are using submit button and by default HTML form generated uses POST action, it call the [HttpPost]

    You can refer this article (from the internet archive as original link is now down): https://web.archive.org/web/20120527133344/http://microsoftmentalist.com:80/2011/09/07/asp-net-mvc-difference-between-httpget-and-httppost-with-example/

    See for example how GET and POST action methods are overloaded.