HttpPost VS属性HTTPGET在MVC:为什么要使用HttpPost? [英] HttpPost vs HttpGet attributes in MVC: Why use HttpPost?

查看:213
本文介绍了HttpPost VS属性HTTPGET在MVC:为什么要使用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) { ... }

这将是不可能的,除非<青霉> <一href=\"http://msdn.microsoft.com/en-us/library/system.web.mvc.actionmethodselectorattribute%28v=vs.108%29.aspx\">ActionMethodSelectorAttributes HTTPGET HttpPost 使用的地方。
这使得它非常简单的创建一个编辑视图。所有的动作链接只是点右后卫到控制器。如果视图模型验证假的,你只是弹出右后卫到编辑视图一次。

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.

我会大胆地说,这是最好的做法,当谈到CRUDish在ASP.NET MVC的东西。

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.

,这将是这个样子。

@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.

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

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