如何确定视图是用于ASP.NET MVC中的GET还是POST?

Fre*_*ice 22 asp.net-mvc

MVC使用动作属性来映射http 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();
 }
Run Code Online (Sandbox Code Playgroud)

在MVC视图中,如何确定视图是用于http get还是http post?


在视图中它是 IsPost

@{
     var Message="";
     if(IsPost)
      {
            Message ="This is from the postback";
      }
       else
    {
            Message="This is without postback";
    }
}
Run Code Online (Sandbox Code Playgroud)

PS:对于点网核心它是:

Context.Request.Method == "POST"
Run Code Online (Sandbox Code Playgroud)

Luk*_*Led 32

System.Web.HttpContext.Current.Request.HttpMethod存储当前的方法.或者只是Request.HttpMethod在视图内部,但如果你需要检查一下,你的方法可能有问题.

考虑使用Post-Redirect-Get模式来重新发布.


Fre*_*ice 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 --><% } %
Run Code Online (Sandbox Code Playgroud)