【问题标题】:How to determine if the view is for GET or POST in ASP.NET MVC?如何确定视图是用于 ASP.NET MVC 中的 GET 还是 POST?
【发布时间】:2011-02-14 16:41:49
【问题描述】:

MVC 使用 action 属性为 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();
 }

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


在视图中是IsPost

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

PS:对于dot net core是:

Context.Request.Method == "POST"

【问题讨论】:

    标签: asp.net-mvc


    【解决方案1】:

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

    考虑使用 Post-Redirect-Get 模式来形成转发。

    【讨论】:

    • 在您的 cshtml 文件中实际上可能需要 IsPost 的一种情况是,如果您在表单帖子中返回使用 Html.Action 的视图。因此,[HttpPost] 路由在验证失败时返回一个视图,例如您可能需要传入已发布的模型,例如:@Html.Action("FormFooPartial", "FormFoo", new { area = "", viewModel = Model }).. 否则您可能会丢失一些用户输入。就我而言,似乎我需要获取和发布的操作方法。
    【解决方案2】:
    <% 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 --><% } %
    

    【讨论】:

      【解决方案3】:

      对于点网核心是:

      Context.Request.Method == "POST"

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-04
        • 2010-09-24
        • 1970-01-01
        • 1970-01-01
        • 2010-09-07
        • 2011-04-01
        • 1970-01-01
        相关资源
        最近更新 更多