MVC 中的 HttpPost 与 HttpGet 属性:为什么使用 HttpPost? [英] HttpPost vs HttpGet attributes in MVC: Why use HttpPost?

查看:48
本文介绍了MVC 中的 HttpPost 与 HttpGet 属性:为什么使用 HttpPost?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我们有 [HttpPost],这是一个可选属性.我知道这限制了调用,因此它只能通过 HTTP POST 请求进行.我的问题是我为什么要这样做?

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?

推荐答案

想象以下内容:

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

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

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

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.

这篇关于MVC 中的 HttpPost 与 HttpGet 属性:为什么使用 HttpPost?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆