asp.net-mvc 如何确定视图是用于 ASP.NET MVC 中的 GET 还是 POST?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4994707/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to determine if the view is for GET or POST in ASP.NET MVC?
提问by FreeVice
MVC use action attributes to map the same view for http get or post:
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();
}
In the MVC view, how can I determine if the view is for http get or http post?
在 MVC 视图中,如何确定该视图是用于 http get 还是 http post?
in Views it is IsPost
在视图中它是 IsPost
@{
var Message="";
if(IsPost)
{
Message ="This is from the postback";
}
else
{
Message="This is without postback";
}
}
PS: For dot net core it is:
PS:对于点网核心,它是:
Context.Request.Method == "POST"
回答by LukLed
System.Web.HttpContext.Current.Request.HttpMethod
stores current method. Or just Request.HttpMethod
inside of view, but if you need to check this, there may be something wrong with your approach.
System.Web.HttpContext.Current.Request.HttpMethod
存储当前方法。或者只是Request.HttpMethod
在视图内部,但如果您需要检查这一点,则您的方法可能有问题。
Think about using Post-Redirect-Get pattern to form reposting.
考虑使用 Post-Redirect-Get 模式来形成重新发布。
回答by FreeVice
<% 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 --><% } %
回答by Dakshal Raijada
For dot net core it is:
对于点网核心,它是:
Context.Request.Method == "POST"
Context.Request.Method == "POST"