Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
547 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...