I'm a newbie when it comes to web programming. I started off with the ASP.NET tutorial project and I made a html page and did all the MVC stuff. I now have an array in my C# code that I'd like to pass to a javascript function. But I don't know how and I can't find anything online.
Is this possible and if so how do I go about it?
Update
So I am trying the below based on initial feedback. My project is .netcore2 so I can't use the System.web stuff. I read online that json.NET lets me do the serializing/deserializing so I'm using that instead.
2nd update
I updated the DeserializeObject to use Dictionary, but still getting the same undefined exception.
Clarifying:
On the Client side I think it's the below code that is throwing up the popup exception. So the response is not succeeding on the C#/MVC/Controller side... I just haven't figured out how to resolve this...
if (response.Status !== "OK") {
alert("Exception: " + response.Status + " | " + response.Message);
Client
<script>
var myRequest = {
key: 'identifier_here',
action: 'action_here',
otherThing: 'other_here'
};
//To send it, you will need to serialize myRequest. JSON.strigify will do the trick
var requestData = JSON.stringify(myRequest);
$.ajax({
type: "POST",
url: "/Home/MyPage",
data: { inputData: requestData }, //Change inputData to match the argument in your controller method
success: function (response) {
if (response.Status !== "OK") {
alert("Exception: " + response.Status + " | " + response.Message);
}
else {
var content = response;//hell if I know
//Add code for successful thing here.
//response will contain whatever you put in it on the server side.
//In this example I'm expecting Status, Message, and MyArray
}
},
failure: function (response) {
alert("Failure: " + response.Status + " | " + response.Message);
},
error: function (response) {
alert("Error: " + response.Status + " | " + response.Message);
}
});
C#/MVC/Controller
[HttpPost]
public JsonResult RespondWithData(string inputData)//JSON should contain key, action, otherThing
{
JsonResult RetVal = new JsonResult(new object()); //We will use this to pass data back to the client
try
{
var JSONObj = JsonConvert.DeserializeObject<Dictionary<string,string>>(inputData);
string RequestKey = JSONObj["key"];
string RequestAction = JSONObj["action"];
string RequestOtherThing = JSONObj["otherThing"];
//Use your request information to build your array
//You didn't specify what kind of array, but it works the same regardless.
int[] ResponseArray = new int[10];
for (int i = 0; i < ResponseArray.Length; i++)
ResponseArray[i] = i;
//Write out the response
RetVal = Json(new
{
Status = "OK",
Message = "Response Added",
MyArray = ResponseArray
});
}
catch (Exception ex)
{
//Response if there was an error
RetVal = Json(new
{
Status = "ERROR",
Message = ex.ToString(),
MyArray = new int[0]
});
}
return RetVal;
}