1

I am doing below to pass Json data to My MVC controller action

Script

 var jInput = $("textarea");
 var count = 0;
 var jsonPackage = "{";
 $.each(jInput, function (i) {
 jInput[i].style.borderColor = "";
 if (jInput[i].value != "") {
 if (count != 0) {
 jsonPackage += ",";
 }
 count++;
 jsonPackage += "'" + jInput[i].id + "':'" + jInput[i].value.replace(/\\/g, "|").replace(/\'/g, "^") + "'";
 }
 });
 jsonPackage += "}";
 $.ajax({
 url: "Appraisal/LegalCheck",
 type: "POST",
 data: JSON.stringify(jsonPackage),
 dataType: "json",
 contentType: "application/json",
 success: function (retValue) {
 alert(retValue);
 }
 });

Controller method

 public Dictionary<string, Illegal[]> LegalCheck(string jsonPackage)
 {
 }

Class

 [Serializable]
 public class Illegal
 {
 public string Phrase { get; set; }
 public int StartIndex { get; set; }
 }

For some reason jsonPackage is always null in the controller method. Sample data that s being passed from the script is,

jsonPackage - {'CommentTextarea_1181_1183':'ghhgghhhgd','CommentTextarea_1181_1184':'Coments','CommentTextarea_1181_1185':'comentss'}

What am I doing wrong here? Why am I getting null in my controller method? Please suggest.

Thanks

Jehof
35.7k11 gold badges127 silver badges156 bronze badges
asked Feb 23, 2012 at 11:48

2 Answers 2

1

try

$.ajax({
 url: "Appraisal/LegalCheck",
 type: "POST",
 data: {jsonPackage:JSON.stringify(jsonPackage)},
 dataType: "json", 
 success: function (retValue) {
 alert(retValue);
 }
 });
answered Feb 23, 2012 at 11:58
1
  • Above change with contentType parameter commented works. but the data comes along with additional backslash and double quote Commented Feb 23, 2012 at 13:49
0

I would guess your JSON string isnt actually being assigned to the jsonPackage variable and so isnt being picked up by your model binder.

for a quick fix try

$.ajax({ 
 url: "Appraisal/LegalCheck", 
 type: "POST", 
 data: "jsonPackage="+JSON.stringify(jsonPackage), 
 dataType: "json", 
 contentType: "application/json", 
 success: function (retValue) { 
 alert(retValue); 
 } 
}); 
answered Feb 23, 2012 at 15:16

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.