Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if the view is for GET or POST in ASP.NET MVC?

Tags:

MVC use action attributes to map the same view for http get or 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?


in Views it is IsPost

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

PS: For dot net core it is:

Context.Request.Method == "POST" 
like image 260
FreeVice Avatar asked Feb 14 '11 16:02

FreeVice


People also ask

How can we detect that a MVC controller is called by post or get?

You can check the Request. HttpMethod property. Save this answer.

How do you know if a view is partial or not?

A partial view is sent via AJAX and must be consumed by JavaScript on the client side, while a View is a full postback. That's it. Normally this means that a View is more of a complete web page and a partial view is reserved for individual sections or controls.

What is get and post in MVC?

Both GET and POST method is used to transfer data from client to server in HTTP protocol but the Main difference between the POST and GET method is that GET carries request parameter appended in URL string while POST carries request parameter in message body which makes it more secure way of transferring data from ...


2 Answers

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.

Think about using Post-Redirect-Get pattern to form reposting.

like image 89
LukLed Avatar answered Sep 20 '22 16:09

LukLed


<% 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 --><% } % 
like image 21
FreeVice Avatar answered Sep 21 '22 16:09

FreeVice