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

2 Answers 2

1

try

$.ajax({
        url: "Appraisal/LegalCheck",
        type: "POST",
        data: {jsonPackage:JSON.stringify(jsonPackage)},
        dataType: "json",            
        success: function (retValue) {
            alert(retValue);
        }
    });
Sign up to request clarification or add additional context in comments.

1 Comment

Above change with contentType parameter commented works. but the data comes along with additional backslash and double quote
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); 
    } 
}); 

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.