I am calling controller POST method via jquery ajax. Controller method is returning 2D array to ajax. I am able to successfully get array in ajax success but it becomes 1D array instead I want it to be 2D array or whatever dimensional array I have sent from controller method.
Here is my controller method:
[HttpPost]
public JsonResult MultiDArrayToView(string s)
{
string[,] table = new string[2, 2];
table[0, 0] = "1";
table[0, 1] = "2";
table[1,0] = "3";
table[1,1] = "4";
var response = new { table = table};
return Json(response);
}
Here is my View code:
<body>
<div>
<form action="/Home/MultiDArrayToView" method="post" id="form">
<input name="s" required/>
<button type="submit">Submit</button>
</form>
</div>
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function () {
$("#form").submit(function (event) {
event.preventDefault(); //prevent default action
var post_url = $(this).attr("action"); //get form action url
var request_method = $(this).attr("method"); //get form GET/POST method
var form_data = new FormData(this); //Creates new FormData object
$.ajax({
url: post_url,
type: request_method,
data: form_data,
contentType: false,
cache: false,
processData: false,
datatype: "json",
success: function (value) {
//here I am getting array from controller method in 'value' but as a 1D array instead I want multidimensional array
debugger;
}
});
});
});
</script>
</body>
Instead of using the matrix:
string[,] table = new string[2, 2];
Use a jagged array
string[][] table = new string[2][2];
This will allow the json serializer to effectively do the conversion.