且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

MVC 中的 HttpPost 与 HttpGet 属性:为什么要使用 HttpPost?

更新时间:2022-11-27 23:01:43

想象一下:

[HttpGet]
public ActionResult Edit(int id) { ... }

[HttpPost]
public ActionResult Edit(MyEditViewModel myEditViewModel) { ... }

这是不可能的,除非 ActionMethodSelectorAttributes HttpGetHttpPost 在哪里使用.这使得创建编辑视图变得非常简单.所有的动作链接都直接指向控制器.如果视图模型验证为假,您只需再次弹回编辑视图.

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.

当涉及到 ASP.NET MVC 中的 CRUDish 事物时,我会大胆地说这是***实践.

I will be bold and say this is best practice when it comes to CRUDish things in ASP.NET MVC.

@TheLight 询问视图中需要什么来完成帖子.它只是一个带有 POST 方法的表单.

@TheLight asked what was needed in the view to accomplish the post. It's simply just a form with method POST.

使用 Razor,这看起来像这样.

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" />
}

这会呈现以下 HTML:

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>

当表单提交时,它会向控制器执行一个 Http Post 请求.HttpPost 属性的动作将处理请求.

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.