0

I am sending a JSON message to a MVC method. When I debug it calls the method but it seems like the data is not there. In other words answerDetail is null.

Can someone give me some advice on what I may be doing wrong. Here's what I have:

The following MVC Controller method:

[HttpPost]
[ActionName("CheckAnswers")]
public void CheckAnswers(AnswerDetail2 answerDetail)
{
    var a = answerDetail;

}

This message is sent to the method:

POST http://127.0.0.1:81/api/Question/CheckAnswers HTTP/1.1
Host: 127.0.0.1:81
Connection: keep-alive
Content-Length: 722
Accept: application/json, text/plain, */*
Origin: http://127.0.0.1:81
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36
Content-Type: application/json;charset=UTF-8
Referer: http://127.0.0.1:81/questions/5
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Cookie: __RequestVerificationToken=4puG_e0..B181

[{"answerId":5,"text":"<p>x</p>","correct":null,"response":false},
 {"answerId":6,"text":"<p>xx</p>","correct":null,"response":false},
 {"answerId":7,"text":"<p>xxx</p>","correct":null,"response":false}]

Here's my AnswerDetail2 class:

public class AnswerDetail2
{
    public int answerId { get; set; }
    public string text { get; set; }
    public Nullable<bool> correct { get; set; }
    public Nullable<bool> response { get; set; }
}

Update: Please note I changed the header. It's actually going to a Web API method so I think it's okay to post an object. The problem is it's not getting accepted.

1
  • 1
    Did you mean to say POST instead of PUT? Also, your POST data is an array of AnswerDetail2, not a single instance. Commented Sep 17, 2013 at 9:47

2 Answers 2

2

U r passing a json string but the paramater u have taken is a class. This wont work.

Try this instead.

[HttpPost]
[ActionName("CheckAnswers")]
public void CheckAnswers(string answerDetail)
{
    var a = answerDetail;
    //deserialize ur json string..
}

and u r 'POST'ing the data. R u making an ajax POST method?

try this

var myObject =
{
    answerId: 123,
    text: "my Text",
    correct: true,
    response: false,   
};

var answerDetail = JSON.stringify(myObject);

$.ajax({
type: "POST",
url: <Controller>/CheckAnswers,
data: answerDetail,
success: function(data){
  //what ever
  }
});
Sign up to request clarification or add additional context in comments.

Comments

0

you can send your requests by ajax with PUT method not by form

Comments

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.