开发者

How to process a POST request in a controller?

开发者 https://www.devze.com 2023-01-26 06:05 出处:网络
It seems that the default is开发者_Go百科 GET; how do I process POST and other HTTP methods?When you send a POST request, the framework will automatically invoke the POST action. So for example if you

It seems that the default is开发者_Go百科 GET; how do I process POST and other HTTP methods?


When you send a POST request, the framework will automatically invoke the POST action. So for example if you have an HTML form:

<% using (Html.BeginForm("Index", "Home", FormMethod.Post)) {%>
    <input type="submit" value="OK" />
<% } %>

It will automatically invoke the POST index action:

[HttpPost]
public ActionResult Index()
{
    ...
}

or you could use jquery to send an AJAX request and specify that you want to POST:

$.post('/home/index', function(result) {
    alert('successfully invoked the POST index action');
});

As far as other verbs are concerned like PUT and DELETE those are only supported in AJAX calls. You cannot specify it in an HTML form. Although there's a workaround. The following form:

<% using (Html.BeginForm("Destroy", "Home", FormMethod.Post)) {%>
    <%= Html.HttpMethodOverride(HttpVerbs.Delete) %>
    <input type="submit" value="OK" />
<% } %>

will invoke this action:

[HttpDelete]
public ActionResult Destroy() {}

The way this works is that the POST verb is used but an additional hidden field is sent along with the request which allows the engine to route to the proper controller action. If you use AJAX then you can specify directly the verb you want:

$.ajax({
    url: '/home/destroy',
    type: 'DELETE',
    success: function(result) {
    }
});


add this attribute to your action method:

[HttpPost]


Just make sure in the aspx that your processing action method is a an action for a form POST and you're good to go:

using(Html.BeginForm("ActionName", "ControllerName") {}

ActionName is the method that will handle the POST.

Or did I misunderstand the question?

0

精彩评论

暂无评论...
验证码 换一张
取 消