Asp.net-Mvc

MVC 中的 HttpPost 與 HttpGet 屬性:為什麼要使用 HttpPost?

  • March 16, 2011

所以我們有 [HttpPost],它是一個可選屬性。我知道這會限制呼叫,因此只能通過 HTTP POST 請求進行。我的問題是我為什麼要這樣做?

想像一下:

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

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

除非ActionMethodSelectorAttributes HttpGetHttpPost在哪裡使用,否則這是不可能的。這使得創建編輯視圖變得非常簡單。所有的動作連結都直接指向控制器。如果視圖模型驗證為假,您只需再次彈回編輯視圖。

當談到 ASP.NET MVC 中的 CRUDish 事物時,我會大膽地說這是最佳實踐。

編輯:

@TheLight 詢問視圖中需要什麼來完成該文章。它只是一個帶有 POST 方法的表單。

使用 Razor,這看起來像這樣。

@using (Html.BeginForm())
{
   <input type="text" placeholder="Enter email" name="email" />
   <input type="submit" value="Sign Up" />
}

這將呈現以下 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屬性的操作將處理請求。

引用自:https://stackoverflow.com/questions/5332275