Question

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)

Was it helpful?

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.

OTHER TIPS

You need the button to be a submit button:

Change:

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

To:

<input type="submit" id="SaveChanges" value="Save" />  
             ^^^^^^

First of all same signature same name method can't be compiled in same controller it will give you the compilation error already have member of same parameter type.

You have to differentiate these two similar name method by different signature.

Regarding HttpPost and HttpGet your get method will be called whenever you have to retrive data or your page load is called for that view.

HttpPost method will be called either you are using button of type submit or your input type is button but using jquery you are giving ajax call on button click and your ajax type is "Post" $.ajax({ url: "Action" type: "Post" },succees: function(){alert('succeed');});

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top