javascript - 如何将数据从 C# 传递到 javascript 函数?

标签 javascript c# asp.net model-view-controller

我是网络编程的新手。我从 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/

相关文章:

javascript - 当单个页面上存在 2 个表单时,如何使用 jQuery 表单验证插件验证 reCaptcha?

c# - SqlDataReader 从 SQL Server 2008 读取位数据类型?

c# - 如何在C#中显示没有任何按钮的消息框

asp.net - ASP.NET中ScriptManager和ScriptManagerProxy之间的区别

javascript - 如果用户中断重定向到新页面,禁用的提交按钮将保持禁用状态

javascript - 如何在 JavaScript 中复制一个对象?

javascript - 如何使用 Javascript 获取 JSON 格式的当前 UTC 时间?

c# - DataContractJsonSerializer 抛出异常预期状态 'Element' .. 遇到 'Text' 名称 '',命名空间 ''

javascript - 如何使用 AngularJS 替换 .asp include?

c# - ASP 文本框调用 javascript 函数