2011-02-14 32 views
18

MVC使用action屬性映射爲HTTP GET或POST了同樣的觀點:如何確定視圖是用於ASP.NET MVC中的GET還是POST?

[HttpGet] 
public ActionResult Index() 
{ 
    ViewBag.Message = "Message"; 
    return View(); 
} 

[HttpPost] 
public ActionResult Index(decimal a, decimal b, string operation) 
{ 
    ViewBag.Message = "Calculation Result:"; 
    ViewBag.Result = Calculation.Execute(a, b, operation); 
    return View(); 
} 

在MVC視圖,我怎麼能確定視圖是HTTP GET或HTTP POST?


在視圖中它是IsPost

@{ 
    var Message=""; 
    if(IsPost) 
     { 
      Message ="This is from the postback"; 
     } 
     else 
    { 
      Message="This is without postback"; 
    } 
} 

回答

29

System.Web.HttpContext.Current.Request.HttpMethod存儲當前方法。或者只是在視圖內的Request.HttpMethod,但如果您需要檢查這一點,您的方法可能會出現問題。

考慮使用Post-Redirect-Get模式來形成重新發布。

9
<% if (System.Web.HttpContext.Current.Request.HttpMethod.ToString() == "GET") { %><!-- This is GET --><% } 
    else if (System.Web.HttpContext.Current.Request.HttpMethod.ToString() == "POST") 
     { %><!--This is POST--><%} 
     else 
     { %><!--Something another --><% } % 
相關問題