Json passed is null in MVC controller method

2019-08-11 12:04发布

问题:

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

回答1:

try

$.ajax({
        url: "Appraisal/LegalCheck",
        type: "POST",
        data: {jsonPackage:JSON.stringify(jsonPackage)},
        dataType: "json",            
        success: function (retValue) {
            alert(retValue);
        }
    });


回答2:

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); 
    } 
});