So we have [HttpPost], which is an optional attribute. I understand this restricts the call so it can only be made by an HTTP POST request. My question is why would I want to do this?
HTTP is a HyperText Transfer Protocol that is designed to send and receive the data between client and server using web pages. HTTPGET and HTTPPOST attributes encode request parameters as key and value pairs in the HTTP request. The HttpGet protocol and the HttpPost protocol provide backward compatibility.
HTTP Post. This verb is used while we have to create a new resource in the database. In HttpPost, data travels in the URL and body. To use HttpPost method, we use HttpPost attribute on the Action method.
An HTTP command used to request a file from a Web server. GET is widely implemented in HTML files (Web pages) for making database queries that do not involve any updating at the server side.
The HTTP POST request is used to create a new record in the data source in the RESTful architecture. So let's create an action method in our StudentController to insert new student record in the database using Entity Framework. The action method that will handle HTTP POST request must start with a word Post.
Imagine the following:
[HttpGet] public ActionResult Edit(int id) { ... } [HttpPost] public ActionResult Edit(MyEditViewModel myEditViewModel) { ... }
This wouldn't be possible unless the ActionMethodSelectorAttributes HttpGet
and HttpPost
where used. This makes it really simple to create an edit view. All the action links just points right back to the controller. If the view model validates false, you just pop right back to the edit view again.
I will be bold and say this is best practice when it comes to CRUDish things in ASP.NET MVC.
EDIT:
@TheLight asked what was needed in the view to accomplish the post. It's simply just a form with method POST.
Using Razor, this would look something like this.
@using (Html.BeginForm()) { <input type="text" placeholder="Enter email" name="email" /> <input type="submit" value="Sign Up" /> }
This renders the following HTML:
<form action="/MyController/Edit" method="post"> <input type="text" name="email" placeholder="Enter email"> <input type="submit" value="Sign Up"> </form>
When the form is submitted, it will perform an Http Post request to the controller. The action with the HttpPost
attribute will handle the request.
Its so you can have multiple Actions that use the same name, you can use the HttpPost attribute to mark which method gets handled on a Post request like so:
public ActionResult ContactUs() { return View(); } [HttpPost] public ActionResult ContactUs(ContactUsModel model) { //do something with model return View(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With