【问题标题】:How to pass data from a C# to javascript function?如何将数据从 C# 传递到 javascript 函数?
【发布时间】: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


【解决方案1】:

有很多方法。

其中一些是直接在 MVC 视图中完成的。您需要将 c# 变量放入视图中。有两种典型的方法可以做到这一点: 1)作为模型 2) 作为 ViewBag 元素

要将其作为模型变量,您需要将数组从控制器传递给 View() 函数。例如

 MyClass[]  myArray = new MyClass[] {  new MyClass("A"), new MyClass("B"), ...};
 View(myArray);

在视图中,您将变量放在视图顶部,如下所示:

 @model  MyClass[]

稍后在视图中将变量分配给“模型”变量。例如

 @Model[0]  

另一种方式是把它赋值给Controller中的ViewBag:

 ViewBag.MyArray = myArray;

然后在视图中就可以访问ViewBag了:

@ViewBag.MyArray[0]

所以现在你需要把它变成 Javascript。这可以通过手动将变量转换为 javascript 代码来完成(如果需要)。有几个软件包可以为您完成这项工作。将 Newtonsoft.Json 视为常见的。 Json 只是一个 javascript 表达式,因此可以通过将其放在 javascript 代码所在的位置来将其“评估”为 javascript:

 <script>
      var myJavascriptArray = @Html.Raw(Json.Convert(ViewBag.MyArray));
</script>

请注意,该数组不能包含任何可能被用户操纵以在您的页面上做坏事的代码。

作为另一种技术,javascript 可以调用以 Json 格式传递数据的 api 控制器。 asp.net 控制器通常会为您进行 JSON 转换。您可以使用来自 Jquery 的 ajax 调用或原始的 javascript“获取”调用来从 api 控制器获取数据。

【讨论】:

    【解决方案2】:

    简短的回答是不能直接从服务器调用客户端上的函数。您需要让客户要求提供信息。

    JQuery 是您在客户端最简单的路径。试试这样的:

    客户端代码

       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);
            }
        });
    

    在服务器端,您需要能够接收请求并将数据发回。

    C#/MVC/控制器代码

    [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;
    }
    

    您需要在控制器声明中使用这些命名空间:

    using System;
    using System.Collections.Generic;
    using System.Web.Script.Serialization;
    using System.Web.Mvc;
    

    这应该会让你顺利上路。希望对您有所帮助!

    【讨论】:

    • 我似乎无法解析 javascriptserializer。至少我在尝试时遇到了未知的参考错误。
    • 看到了更新。如果您使用的是 .NET Core,则必须改用 Newtonsoft.Json 或 Microsoft.AspNet.Mvc.Formatters.Json 对象。
    • 您可以创建一个新的类/视图模型并使用模型绑定将数据传递给控制器​​,而不是使用 JavaScriptSerializer。
    • @ColbyBoren 我想将数据从 C# 传递到 JavaScript 函数。我想我已经将它设置为使用 Json.NET 执行与 JavaScriptSerializer 描述的等效操作,但是某些事情没有按预期工作,因为我收到一个说明未定义异常的弹出窗口。当我查看网络选项卡时,POST 似乎正在工作,但我不知道那里出了什么问题。
    • @ToddCopeland 所以经过几天的调试,我发现问题是 RetVal 返回一个未定义的结果。我不知道该怎么办。我也不知道 JSONObj 段在您提供的代码 sn-p 中应该做什么。
    【解决方案3】:

    我的工作,

    在c#中

    protected string arrayElements = String.Join("_separator_",yourArray);
    

    在 aspx 页面中

    <script>
     var arr = arrayElements;
    </script>
    

    并在外部 js 文件中使用arr

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-03
      • 1970-01-01
      • 1970-01-01
      • 2014-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-10
      相关资源
      最近更新 更多