简体   繁体   English

2D javascript数组到c#datatable?

[英]2D javascript array to c# datatable?

I have a 2D javascript array that is filled with user data and checked for valid data. 我有一个2D javascript数组,其中填充了用户数据并检查了有效数据。

How do I go about getting that 2D array passed to my c# code behind page? 我如何将2D数组传递给我的c#代码页面后面? I am going to use the c# code to push it to a database after further processing. 在进一步处理之后,我将使用c#代码将其推送到数据库。

From searching it seems like I need to get it to some sort of json to pass it to the c# code, but i'm at a complete loss on how to do that exactly and then what to do once I get it to the c# code. 从搜索开始,似乎我需要将它转换为某种类型的json以将其传递给c#代码,但是我完全失去了如何准确地执行此操作,然后在将其转换为c#代码后该怎么做。

Javascript array looks like this Javascript数组看起来像这样

[["Q458","","100","85"],
["Q459","TS","90","65"],
["Q460","","80","15"]]

There is a simple way to achieve this with the Newtonsoft.Json library (available for download via NuGet Package Manager - in Visual Studio click Tools -> Library Package Manager -> Manage NuGet Packages for this solution and search for "Json"). 有一个简单的方法可以使用Newtonsoft.Json库(可通过NuGet包管理器下载 - 在Visual Studio中单击工具 - >库包管理器 - >管理此解决方案的NuGet包并搜索“Json”)。

First you send this array to your code-behind - probably via AJAX request supplying your array as a parameter. 首先,您将此数组发送到您的代码隐藏 - 可能是通过AJAX请求提供您的数组作为参数。 To create a JSON string out of your array object, use the JSON-js ( https://github.com/douglascrockford/JSON-js ) library's stringify function as follows: 要从数组对象中创建JSON字符串,请使用JSON-js( https://github.com/douglascrockford/JSON-js )库的stringify函数,如下所示:

var jsonArrayString = JSON.stringify( your_array );

This string you will now send to your server and use Newtonsoft.Json to deserialize to an two dimensional list or array: 此字符串现在将发送到您的服务器并使用Newtonsoft.Json反序列化为二维列表或数组:

JsonConvert.DeserializeObject<List<List<string>>>( yourJsonString );
or
JsonConvert.DeserializeObject<string[,]>(yourJsonString );

To expand on MZetko's answer, here's a method you can use with jQuery and Json.Net. 为了扩展MZetko的答案,这里有一个可以与jQuery和Json.Net一起使用的方法。

First, you'll need to set up a way to send the js array to your c# code. 首先,您需要设置一种将js数组发送到c#代码的方法。 You can use something like this: 你可以使用这样的东西:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

 <script>

        var items = [["Q458", "", "100", "85"], ["Q459", "TS", "90", "65"], ["Q460", "", "80", "15"]];
        sendToDb(items);

        function sendToDb(inArr) {
            var inString = JSON.stringify(inArr);

            $.ajax({
                url: "/Handlers/some-generic-handler.ashx",
                dataType: 'json',
                type: 'post',
                data: { myVar: inString },
                success: function (data) {
                    if (data.success == true) {
                        alert("Here's the first element in the array: " + data.firstElement)
                        alert(data.message);
                    }

                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert(xhr.status);
                    alert(thrownError);
                }
            });
        }
 </script>

Now, you'll need to build a handler that will answer the ajax request. 现在,您需要构建一个将回答ajax请求的处理程序。 This page will use Json.Net. 该页面将使用Json.Net。 The code will look something like this: 代码看起来像这样:

public class some_generic_handler : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        string myVar = "";
        if (!string.IsNullOrEmpty(System.Web.HttpContext.Current.Request.Form["myVar"])) { myVar = System.Web.HttpContext.Current.Request.Form["myVar"].Trim(); }

        var myArr = JsonConvert.DeserializeObject<List<List<string>>>(myVar);

        string firstElement = myArr[0][0];

        string response = String.Format(@"{{ ""success"" : true, ""message"" : ""Cool! We're done."", ""firstElement"" : ""{0}"" }}", firstElement);

        context.Response.ContentType = "application/json";
        context.Response.Write(response);
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

Be sure to install Json.Net by PM> Install-Package Newtonsoft.Json, and then include the following reference: 请务必通过PM> Install-Package Newtonsoft.Json安装Json.Net,然后包含以下参考:

using Newtonsoft.Json;

This demo will convert the js array to a string, send it to your handler page, the handler page will deserialize that string to ac# array, send back the first element in the array to the initial page, and then the initial page will alert the first element. 此演示将js数组转换为字符串,将其发送到处理程序页面,处理程序页面将该字符串反序列化为ac#array,将数组中的第一个元素发送回初始页面,然后初始页面将发出警报第一个元素。 In your application, you would use the handler page to insert data into your db table. 在您的应用程序中,您将使用处理程序页面将数据插入到db表中。

you can pass this from the client side to the server side using asp:HiddenField 您可以使用asp:HiddenField将其从客户端传递到服务器端

Client 客户

 <asp:HiddenField runat="server" ID="myhf" Value="[['Q458','','100','85'],
                           ['Q459','TS','90','65'],['Q460','','80','15']]"/>

Server 服务器

    var ser = new System.Web.Script.Serialization.JavaScriptSerializer();
    var strArray = ser.Deserialize<string[][]>(myhf.Value);

now strArray is a 2D array you can loop through it and do you database insertion. 现在strArray是一个2D数组,你可以遍历它并进行数据库插入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM