GibboK
GibboK

Reputation: 73978

Is it possible to use [HttpPost] attribute on JsonResult

I use MVC 3 in Asp.net I need to send HTTP POST date to a Control. The control should send back some JSON as response. At the moment I'm using this code, but I'm not able to get the Form field in the collection .

Any idea what is wrong?

         [HttpPost]
            public JsonResult LogOn(FormCollection collection, string returnUrl)
            {
    ...
return this.Json(new { success = "true", msg = messages[0] });
    }

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <h1>
        Test LogOn</h1>
    <form action="/Controller/LogOn" method="post">
    UserName:
    <input type="text" name="UserName"><br>
    Password:
    <input type="text" name="Password"><br>
    RememberMe:
    <input type="hidden" name="RememberMe" value="true">
    <input type="submit" value="Submit">
    </form>
</body>
</html>

Upvotes: 1

Views: 1944

Answers (2)

Lews Therin
Lews Therin

Reputation: 10995

Yes, you can. JsonResult is an ActionResult and doesn't have anything to do with POST or GET requests.
Make sure you have wrapped your inputs with

@using(Html.BeginForm())

or 
<form action="" method="">
</form>

Not sure how you are accessing your fields.. Are you doing FormCollection["form"]? It should be formCollection["Password"], formCollection["UserName"] etc..

Upvotes: 0

archil
archil

Reputation: 39501

Yes, it is possible. If there was problem with HttpPostAttribute, you would not have been able to get inside LogOn method. You should re-check that fields are sent from client and those fields are put inside request body, not query string. You could check it with chrome for example, by inspecting network traffic or simply by debugging HttpContext.Current.Request.Form property

Upvotes: 1

Related Questions