Reputation: 2697
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"
Upvotes: 25
Views: 30789
Reputation: 15799
When checking for "postback" in ASP.NET CORE 7
, you should also check if the model is valid like so:
if(ViewData.ModelState.IsValid && Context.Request.Method == "POST")
{
<p><strong>Yes I am Postback and Valid!</strong></p>
}
Upvotes: 1
Reputation: 2697
<% 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 --><% } %
Upvotes: 10
Reputation: 31842
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.
Upvotes: 34