10

I upgraded from MVC4 beta to RC and the latest autofac. The following action was binding properly, but now both parameters are null. I see they changed things about the Formatters and such but I am not sure what caused my problem

[HttpPost]    
RedirectModel MyAction(string value1, string value1)

REQUEST

Method: POST
Accept: application/json
URL: api/controller/myaction
BODY: {"value1":"1000", "value2":"foo"}
Thad
  • 1,518
  • 2
  • 21
  • 37

2 Answers2

20

When you want to avoid using a DTO object, try this:

[HttpPost]    
RedirectModel MyAction(dynamic value1, dynamic value2) {
    string sValue1 = value1;
    string sValue2 = value2;
mhu
  • 17,720
  • 10
  • 62
  • 93
  • 2
    You are a hero. This is the only viable solution in my very specific case. I can't believe I didn't think of it before. I wish I could give you additional upvotes. Cheers. – samuelesque Oct 24 '12 at 16:17
11

Not really sure why the change from Beta, but I was able to make it work by changing the action signature to:

[HttpPost]    
RedirectModel MyAction(MyActionDTO dto)

and defining MyActionDTO as

 public class MyActionDTO 
 {
        public string value1 { get; set; }
        public string value2 { get; set; }
 }

It was throwing an exception about not being able to bind to multiple body parameters using the two string paramaters. I guess using the DTO object more closely represents what you're sending in the AJAX call (a JSON object).

Jim Harte
  • 2,593
  • 3
  • 23
  • 20
  • 2
    Adding [FromBody] to the parameters did not having any effect, the parameters were still null. – Thad Jun 11 '12 at 13:05
  • That does work, but I was hoping not to have to change it. We do have a few calls that have a single string in the body. I not sure why a single primitive types is required to be on the query string. – Thad Jun 11 '12 at 20:48
  • According to this:http://blogs.msdn.com/b/jmstall/archive/2012/04/16/how-webapi-does-parameter-binding.aspx, you can pass one and only one item in the body. So, if you want to pass a string value, you can do that, just pass the value without wrapping it as a JSON string. – Jim Harte Jun 12 '12 at 16:16
  • asp.net site updated today with more info: http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-1 Note you must prefix the value with an equal sign (=) when posting a simple value in the body – Jim Harte Jun 16 '12 at 02:04
  • Thank you very much , binding parameters to C# class works fine for me .I want to ask why I can send parameters only to HttpPost WebApi actions , can I send parameters to HttpGet Web Api action ? – Omar Isaid Jan 22 '18 at 17:56
  • @OmarIsaid, a get request does not have a request body. But you can still send parameters in the url/query. It's just less suited for some cases. – Doh09 May 20 '19 at 10:33