I'm a newbie when it es 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 core2 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;
}
I'm a newbie when it es 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 core2 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;
}
Share
Improve this question
edited Mar 18, 2019 at 22:34
elllo
asked Mar 17, 2019 at 4:16
ellloelllo
792 silver badges10 bronze badges
3
- The first step is to get the c# array into the view. This can be done by making it the model for the view. In the controller in the View() call pass the array. In the view at the top put @model your_type[]. In the view reference it as the variable Model. To get it into a JavaScript call, change it into Json. And set a script variable equal to the Json string as @Html.Raw(...). Just put it where you would use it in JavaScript in a <script> tag. – Mike Wodarczyk Commented Mar 17, 2019 at 4:43
- Please update your post to include the code you've tried. – HaC Commented Mar 17, 2019 at 4:44
- Added my attempt, but I'm getting undefined errors and unsure how to resolve. – elllo Commented Mar 18, 2019 at 21:21
3 Answers
Reset to default 2The short answer is that a function on the client can't be called directly from the server. You will need to have the client ask for the information.
JQuery is your easiest path on the client side. Try something like this:
Client Code
var myRequest = {
key: 'Put an identifier here', //Pack myRequest with whatever you need
action: 'Put an action here',
otherThing: 'Put other stuff 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: "Your URL goes here",
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 {
//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);
}
});
On the server side, you will need to be able to receive the request and send the data back.
C# / MVC / Controller Code
[HttpPost]
public JsonResult YourMethodName(string inputData)//JSON should contain key, action, otherThing
{
JsonResult RetVal = new JsonResult(); //We will use this to pass data back to the client
try
{
var JSONObj = new JavaScriptSerializer().Deserialize<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];
//populate array here
//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;
}
You'll need these namespaces in your controller declaration:
using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Web.Mvc;
That should get you well on your way. Hope it helps!
What I do,
in c#
protected string arrayElements = String.Join("_separator_",yourArray);
in aspx page
<script>
var arr = arrayElements;
</script>
and use arr
in external js files.
There are a number of ways.
A few of them are directly done in the MVC view. You need to get the c# variable into the view. There are 2 typical ways of doing this: 1) as a model 2) as a ViewBag element
To do it as a model variable, you want to pass the array into the View() function from the controller. e.g.
MyClass[] myArray = new MyClass[] { new MyClass("A"), new MyClass("B"), ...};
View(myArray);
in the view you refer to the variable put putting something like this at the top of the view:
@model MyClass[]
Later in the view the variable is assigned to the "Model" variable. e.g.
@Model[0]
The other way is to assign it to the ViewBag in the Controller:
ViewBag.MyArray = myArray;
Then in the view you can access the ViewBag:
@ViewBag.MyArray[0]
So now you need to get it into Javascript. This can be done by translating the variable into javascript code manually (if you want). There are several packages that do a great job of this for you. See Newtonsoft.Json as a mon one. Json is just a javascript expression so it can be "evaluated" as javascript by putting it where javascript code would go:
<script>
var myJavascriptArray = @Html.Raw(Json.Convert(ViewBag.MyArray));
</script>
Be careful that the array cannot contain any code that could be manipulated by users to do bad things on your page.
As another technique, the javascript can call an api controller that delivers the data in Json format. The asp controller will typically do the JSON conversion for you. You use an ajax call from Jquery, or a raw javascript "fetch" call to get the data from the api controller.