Sunday, 23 December 2018

AcceptVerbs selector

AcceptVerbs selectors are used to controlling, the invocation of an action method based on the request type. In the example below, the "Edit" method that is decorated with GET acceptverb responds to the GET request, whereas the other "Edit" method responds to POST request. The default is GET. So, if you don't decorate an action method with any accept verb, then, by default, the method responds to GET request.

public class HomeController Controller
{
    [AcceptVerbs(HttpVerbs.Get)]
    public ActionResult Edit(int id)
    {
        Department dept= GetDepartmentsFromDB(id);
        return View(department);
    }
    
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Save(Department  dept)
    {
        if (ModelState.IsValid)
        {
           return RedirectToAction("Index");
        }
        return View(department);
    }
}

HttpGet and HttpPost work similar to AcceptVerbs attribute. Below is the same exmple:

public class HomeController Controller
{
    [HttpGet]
    public ActionResult Edit(int id)
    {
        Department  dept= GetDepartmentsFromDB(id);
        return View(department);
    }
    
    [HttpPost]
    public ActionResult Save(Department dept)
    {
        if (ModelState.IsValid)
        {
           return RedirectToAction("Index");
        }
        return View(department);
    }
} 

No comments:

Post a Comment