Wednesday 9 September 2009

Why use the MVC AcceptVerbs attribute?

The [AcceptVerbs] attribute can be applied to action methods in a controller so that the appropriate overloaded method is invoked for a given request. ASP.NET MVC will automatically dispatch a request to the appropriate action method based on the HTTP verb.

The advantage of differentiating methods based on HTTP verb is that the same URL can be used for multiple opuposes (e.g. display and edit). This could be done with 2 separate URLs but the downside here is that it makes bookmarking pages difficult. For example, if an error occurs during a POST and we direct the user to a different page (one that displays the eror message) and the user bookmarks tghis page they have a bookmark to an 'invalid' page.

By using the [AcceptVerbs] attribute we can have a single URL that is sagfe to bookmark even after a POST.

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Edit(int id) {
   // code snipped
   // this is invoked when viewing the edit page
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection formValues) {
   // code snipped
   // this is invoked when POSTing data to the edit page
}