2

Javascript:

$.post("/DataAPI/messageProcessor", { query: "Hello World!" }, function (data) {
  Handle(data); 
}
});

Controller:

[System.Web.Http.AcceptVerbs("Post")]
[System.Web.Http.ActionName("messageProcessor")]
public ResponseModel messageProcessor(string query)
{
  ResponseModel model=DoStuff(query);
  return model;
}

How do I access query from the controller. It always arrives as query == null. There is Request object available too but I am not sure how to navigate through its members to reach my "Hellow World!".

tereško
  • 58,060
  • 25
  • 98
  • 150
AstroSharp
  • 1,872
  • 2
  • 22
  • 31

3 Answers3

2

You need to pass name-value pairs from the client:

$.post("/DataAPI/messageProcessor"
          , { query: "Hello World!" }
          , function (data) {} );

Check jQuery.Post for more details.

Leigh
  • 28,765
  • 10
  • 55
  • 103
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
1

try this :

$.post("/DataAPI/messageProcessor", { 'query' : 'Hello World!' }, function (data) {
     Handle(data); 
   }
});
Behnam Esmaili
  • 5,835
  • 6
  • 32
  • 63
1

Thanks to a coworker. Solution is as following:

public class QueryClass 
{
public string query { get; set; }
}

public ResponseModel messageProcessor(QueryClass query)
{
  ResponseModel model=DoStuff(query.query);
  return model;
}
AstroSharp
  • 1,872
  • 2
  • 22
  • 31
  • 1
    Doesn't surprise me that this works, but I'm still surprised that the solutions posted by others did NOT work. – Eric Petroelje Dec 17 '12 at 21:33
  • Yes. you are just passing a string to controller and it must get retrieve when you specified datatype as 'string'. If you pass some JSON object, you must need to specify datatype as 'object'. Not sure how this works. But can try this approach if i come across your issue!. – RGR Dec 18 '12 at 04:55
  • Sorry, but I still don't understand why this work and others don't. ASP.NET MVC allows you to receive a simple string, an int, a complex type, a complex type plus simple parameters, etc. It is smart enough to map the query string or form body into any parameters or object properties from want you want to receive. I'm completely sure that a $.post('/MyController/Action1', { query : 'do stuff'}) will definitely invoke MyController.Action1(String data) – João Simões Dec 18 '12 at 09:20
  • I meant MyController.Action1(String query) – João Simões Dec 18 '12 at 10:15