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"}

2 Answers 2

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;
Sign up to request clarification or add additional context in comments.

1 Comment

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.
12

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).

6 Comments

Adding [FromBody] to the parameters did not having any effect, the parameters were still null.
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.
According to this:blogs.msdn.com/b/jmstall/archive/2012/04/16/…, 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.
asp.net site updated today with more info: asp.net/web-api/overview/working-with-http/… Note you must prefix the value with an equal sign (=) when posting a simple value in the body
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 ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.