ajax 返回json null,通过AJAX将JSON数据传递到控制器时为NULL值

Trying to pass following JSON from View to Controller

{

"allselected": false,

"selectedIds": ["", "all"],

"targetControl": "Studieniva",

"targetSource": "studienivalist",

"dependency": [{

"name": "ShopNo",

"selectedvalues": "311"

}, {

"name": "Institution",

"selectedvalues": ["all", "UIO"] // THIS IS COMING AS NULL AT CONTROLLER . OCCURS ONLY WHEN MULTIPLE ITEMS UNDER dependency

}]

}

Javascript code for sending request is like below (trying to make multiple requests at the same time and based on the response of each request loading some dropdowns )

var targetcontrols_array = targetControl.split(',');

var targetsource_array = targetSource.split(',');

const arrOfPromises = targetcontrols_array.map(function(item, index) {

var control_name = item;

var source = targetsource_array[index];

var request_data = JSON.stringify({ allselected: allselected_flag, selectedIds: selectedvalues, targetControl: control_name, targetSource: source, dependency: dependencyOptions });

console.log("req:"+request_data); //SAMPLE JSON ADDED On TOP

return new Promise((resolve) => {

$.ajax({

url: action_url,

type: 'POST',

traditional: true,

async: false,

data: request_data,

contentType: "application/json; charset=utf-8",

dataType: 'json',

success: function (response) {

//process response

}

})

});

});

Promise.all(arrOfPromises);

MVC controller action is like below

[HttpPost]

public JsonResult CascadingDropDown(DynamicFormSelectModel model)

{

model.dependency values are not coming correctly . Observing that the value of SelectedValues is NULL in some cases

( OCCURS ONLY WHEN MULTIPLE ITEMS UNDER dependency )

}

public class DynamicFormSelectModel

{

public bool allselected { get; set; }

public string[] selectedIds { set; get; }

public string targetSource { set; get; }

public string targetControl { set; get; }

public List dependency { set; get; }

}

public class DynamicFormDependencyOptions

{

public string Name { get; set; }

public string SelectedValues { get; set; }

}

While trying to read the request model.dependency values , sometimes getting NULL , even if values are passed from View (Example attached JSON passing 2 values "name": "Institution",

"selectedvalues": ["all", "UIO"] , but in controller i am getting NULL

1cb69b716585458fb9fd4ff5c2b3582d.png

. OCCURS mostly WHEN MULTIPLE ITEMS are present under dependency property and no idea why its coming as NULL

回复1public class DynamicFormDependencyOptions

{

public string Name { get; set; }

public string SelectedValues { get; set; }

}

change it to

public class DynamicFormDependencyOptions

{

public string Name { get; set; }

public string[] SelectedValues { get; set; }

}

this code has the SelectedValues as string object but the data is in string Array form

make SelectedValues a string Array and You'll get it ....

and change your following code accordingly to parse the string array like you are doing for selectedIds.