PUT or DELETE verb in ASP.NET MVC on HTML form

蓝咒 提交于 2019-11-30 17:41:40

Since no one really answered it here, I'll add my .02

MVC adds the following field to the html form (used for example when using Html.BeginForm()) to support this. Even though HttpPut and HttpDelete are not actually supported for Html5 (they were at one point and then removed from the draft specification), the server libs for MVC will properly route the request to your HttpDelete or HttpPut method when the following form field is posted with your HttpPost request:


@using (Html.BeginForm("SomeAction"){ 
   @Html.HttpMethodOverride(HttpVerbs.Delete)
}

HTML forms (up to HTML version 4 and XHTML 1) only support GET and POST as HTTP request methods. XHTML 2.0 will support GET, POST, PUT and DELETE for forms.

A workaround for this for methods through POST by using a hidden form field which is read by the server and dispatch accordingly.

For now, you may consider using [HttpPost] now or use XmlHttpRequest to use Put verb on your request.


UPDATE

You may use SimplyRestfulRouteHandler from MvcContrib

It quite simple, register this on RegisterRoutes

public static void RegisterRoutes(RouteCollection routes)
{
     SimplyRestfulRouteHandler.BuildRoutes(routes);
}

Add a hidden field like this with name _method inside your form

<input type="hidden" name="_method" value="put" />

This would be good to go.

You could use $.ajax to submit the form with the correct verb

Here is an example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!