Detecting a direct post to a Controller Action
Is there a way of detecting if a Controller is getting posted to directly, or the action is a r开发者_开发技巧esult of a previous form being posted?
Not sure if I understand your question, but if you are asking about the difference between a user typying in an address into their browser's address bar and pressing enter (accessing your page via the GET verb) vs. being already on a page and hitting a form submit button (usually a POST verb, though it can sometimes also be a GET) then you can look at the value of the HttpRequest.HttpMethod property:
public ActionResult MyMethod() {
if(this.Request.HttpMethod == "POST") {
// form submitted
}
if(this.Request.HttpMethod == "GET") {
// accessed directly
}
}
If you want to restrict your action method to only handle a particular http verb you can also use attributes:
[HttpGet]
public ActionResult MyMethod() {
// only invoked if the request is a GET
}
[HttpPost]
public ActionResult MyMethod(string formInput) {
// only invoked if the request is a POST
}
精彩评论