Asp.net-Mvc

如何創建一個從 httpget 獲取相同參數的 httppost?

  • November 2, 2012

我有一個控制器來顯示一個模型(使用者),並且想創建一個螢幕,只需一個按鈕即可啟動。我不想要表單中的欄位。我已經在 url 中有 id。我怎樣才能做到這一點?

利用

$$ ActionName $$屬性 - 這樣您可以讓 URL 看似指向相同的位置,但根據 HTTP 方法執行不同的操作:

[ActionName("Index"), HttpGet]
public ActionResult IndexGet(int id) { ... }

[ActionName("Index"), HttpPost]
public ActionResult IndexPost(int id) { ... }

或者,您可以檢查程式碼中的 HTTP 方法:

public ActionResult Index(int id)
{
   if (string.Equals(this.HttpContext.Request.HttpMethod, "POST", StringComparison.OrdinalIgnoreCase))
   { ... }
}

在這方面有點晚了,但我找到了一個更簡單的解決方案,我認為這是一個相當常見的案例,你在 GET 上提示(“你確定你想要blah blah blah嗎?”)然後使用 POST 採取行動相同的論點。

解決方案:使用可選參數。不需要任何隱藏欄位等。

注意:我只在 MVC3 中測試過這個。

   public ActionResult ActivateUser(int id)
   {
       return View();
   }

   [HttpPost]
   public ActionResult ActivateUser(int id, string unusedValue = "")
   {
       if (FunctionToActivateUserWorked(id))
       {
           RedirectToAction("NextAction");
       }
       return View();
   }

最後一點,您不能使用 string.Empty 代替,""因為它必須是編譯時常量。這是一個為其他人提供有趣評論的好地方:)

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