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

时间:2019-03-17 04:17:00

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

关于Web编程,我是一个新手。我从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;
    }

3 个答案:

答案 0 :(得分: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;

那应该可以让您顺利前进。希望对您有帮助!

答案 1 :(得分:1)

我做什么

在c#

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

在aspx页面中

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

并在外部js文件中使用arr

答案 2 :(得分:0)

有很多方法。

其中一些是直接在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控制器获取数据。

相关问题