【发布时间】:2019-08-07 18:49:07
【问题描述】:
我是网络编程的新手。我从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/控制器
[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#数组放到视图中。这可以通过使其成为视图的模型来完成。在 View() 调用中的控制器中传递数组。在顶部的视图中放置@model your_type[]。在视图中将其作为变量 Model 引用。要将其转换为 JavaScript 调用,请将其更改为 Json。并设置一个等于 Json 字符串的脚本变量为@Html.Raw(...)。只需将它放在您将在 JavaScript 中使用的
-
请更新您的帖子以包含您尝试过的代码。
-
添加了我的尝试,但我遇到了未定义的错误并且不确定如何解决。
标签: javascript c# asp.net model-view-controller