我是网络编程的新手。我从 ASP.NET
教程项目开始,制作了一个 html 页面并完成了所有 MVC
内容。现在,我的 C#
代码中有一个数组,我想将其传递给 javascript
函数。但我不知道怎么做,而且在网上找不到任何东西。
这可能吗?如果可以,我该怎么做?
更新
所以我根据初步反馈尝试以下操作。我的项目是.netcore2,所以我无法使用System.web 的东西。我在网上读到 json.NET 让我可以进行序列化/反序列化,所以我改用它。
第二次更新
我更新了 DeserializeObject 以使用 Dictionary,但仍然遇到相同的未定义异常。
澄清:
在客户端,我认为下面的代码引发了弹出异常。所以响应在 C#/MVC/Controller 端没有成功...... 我只是不知道如何解决这个问题......
if (response.Status !== "OK") {
alert("Exception: " + response.Status + " | " + response.Message);
客户端
<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;
}
最佳答案
我做什么,
在 C# 中
protected string arrayElements = String.Join("_separator_",yourArray);
在aspx页面
<script>
var arr = arrayElements;
</script>
并在外部js文件中使用arr
。
关于javascript - 如何将数据从 C# 传递到 javascript 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55203792/