Wednesday, April 1, 2015

actionverbs-in-mvc

ActionVerbs:

In this section, you will learn about ActionVerbs selectors attribute.
The ActionVerbs selector is used when you want to control the selection of an action method based on Http request method. For example, you can define two different action methods with the same name but one action method responds to an HTTP Get request and another action method responds to an HTTP Post request.
MVC framework supports different ActionVerbs, such as HttpGet, HttpPost, HttpPut, HttpDelete, HttpOptions & HttpPatch. You can apply these attributes to action method to indicate the kind of Http request the action method supports. If you do not apply any attribute then it considers GET request by default.
The following figure illustrates HttpGET and HttpPOST action verbs.
actionverbs
ActionVerbs
The following table lists the usage of http methods:
Http methodUsage
GETTo retrieve the information from the server. Parameters will be appended in the query string.
POSTTo create a new resource.
PUTTo update an existing resource.
HEADIdentical to GET except that server do not return message body.
OPTIONSOPTIONS method represents a request for information about the communication options supported by web server.
DELETETo delete an existing resource.
PATCHTo full or partial update the resource.
Visit W3.org for more information on Http Methods.
The following example shows different action methods supports different ActionVerbs:
ActionVerbs

public class StudentController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult PostAction()
    {
        return RedirectToAction("Index");
    }


    [HttpPut]
    public ActionResult PutAction()
    {
        return RedirectToAction("Index");
    }

    [HttpDelete]
    public ActionResult DeleteAction()
    {
        return RedirectToAction("Index");
    }

    [HttpHead]
    public ActionResult HeadAction()
    {
        return RedirectToAction("Index");
    }
       
    [HttpOptions]
    public ActionResult OptionsAction()
    {
        return RedirectToAction("Index");
    }
       
    [HttpPatch]
    public ActionResult PatchAction()
    {
        return RedirectToAction("Index");
    }
}

You can also apply multiple http verbs using AcceptVerbs attribute. GetAndPostAction method supports both, GET and POST ActionVerbs in the following example:
AcceptVerbs to apply multiple ActionVerbs

[AcceptVerbs(HttpVerbs.Post | HttpVerbs.Get)]
public ActionResult GetAndPostAction()
{
    return RedirectToAction("Index");
}

Points to Remember :

  1. ActionVerbs are another Action Selectors which selects an action method based on request methods e.g POST, GET, PUT etc.
  2. Multiple action methods can have same name with different action verbs. Method overloading rules are applicable.
  3. Mulitple action verbs can be applied to a single action method using AcceptVerbs attribute.

No comments:

Post a Comment