简体   繁体   English

如何使用带有WebMatrix环境的C#.net Web-Pages中的AJAX在服务器端传递和访问对象数组?

[英]How can I pass and access an array of objects on the server-side using AJAX in the C#.net Web-Pages with WebMatrix environment?

Firstly, I have already tried to find this answer on my own. 首先,我已经尝试过自己找到这个答案。 I found a couple of pages on the topic: 我在这个主题上发现了几页:

http://forums.asp.net/t/1934999.aspx?Convert+any+json+string+to+an+array+or+object+in+c+ (This one uses a JSON string, and all, but it is an object and not an array of objects, so it doesn't seem to apply here). http://forums.asp.net/t/1934999.aspx?Convert+any+json+string+to+an+array+or+object+in+c+ (这个使用JSON字符串,所有,但它是一个对象而不是一个对象数组,因此它似乎不适用于此)。

Convert json to a C# array? 将json转换为C#数组? (Here, it seems to have relevant answers, but none of them have helped me [probably because I am not handling this correctly on the server-side]). (这里,它似乎有相关的答案,但它们都没有帮助我[可能是因为我没有在服务器端正确处理这个])。

Now, I have the following simple $.ajax request in jQuery: 现在,我在jQuery中有以下简单的$.ajax请求:

$("#savePageBtn").click(function () {
    $.ajax({
        url: "/AJAX Pages/Compute_Save_Edit_Page.cshtml",
        async: false,
        type: "POST",
        data: { "objectArr": jsonArr }, //more on exactly what jsonArr contains below...
        success: function (response) {
            console.log(response);
        },
        error: function (jqXHR, textStatus, error) {
            alert("Oops! It appears there has been an AJAX error.\n\nPlease check the page you were attempting to edit.\n\n Error: " + textStatus + ".\n\nError Type: " + error + ".");
        }
    });
});

I have also tried: data: JSON.stringify(jsonArr), for the data line, but they both give me internal server errors of the code 500 when I try to access a property of a given object. 我也试过: data: JSON.stringify(jsonArr),用于数据行,但是当我尝试访问给定对象的属性时,它们都给出了代码500的内部服务器错误。 Reading these errors, I can tell that the data is in "string" format (with JSON syntax, I'm sure) so I am not able to access the data as I would like. 阅读这些错误,我可以看出数据是“字符串”格式(使用JSON语法,我确定)所以我无法按照我的意愿访问数据。 Even after I try to use C#'s Json.Decode method. 甚至在我尝试使用C#的Json.Decode方法之后。

Here is the server-side code I have so far (Compute_Save_Edit_Page.cshtml): 这是我到目前为止的服务器端代码(Compute_Save_Edit_Page.cshtml):

@{
    Layout = "";

    if (IsAjax)
    {
        var reader = new StreamReader(Request.InputStream);
        var json = reader.ReadToEnd();
        var objectArr = Json.Decode(json);

        for (var i = 0; i < objectArr.Length; i++)
        {
<!--      -->@:@objectArr[i].objectName;
<!--      --><br/>
        }
    }
    else
    {
        Context.RedirectLocal("~/");
    }
}

I think I know what I need, but I can't seem to get anything to convert the JSON string back into an array of objects, like I want. 我想我知道我需要什么,但我似乎无法将JSON字符串转换回对象数组,就像我想要的那样。

In jQuery I have been accessing this exactly like you would expect. 在jQuery中,我一直在访问它,就像你期望的那样。 To get the object name of an object at the first index, for instance, I would type: jsonArr[0].objectName 例如,要在第一个索引处获取对象的对象名,我将键入: jsonArr[0].objectName

I would like to be able to get this accessible in much the same way once I have it on the server-side, but nothing I try works. 一旦我在服务器端拥有它,我希望能够以相同的方式访问它,但我尝试的任何工作都没有。

Additional Info: 附加信息:

It's appropriate to mention that the array of objects contains objects that don't all have the same properties (which is why trying the top answer in the second link I provided won't work, if I'm even understanding it correctly). 值得一提的是,对象数组包含的对象并不都具有相同的属性(这就是为什么在我提供的第二个链接中尝试顶部答案不起作用,如果我甚至正确理解它的话)。

Here is a sample of a few objects in the array of objects (in no real particular syntax): 以下是对象数组中的一些对象的示例(没有真正的特定语法):

Object { 
    caption: "", 
    fileName: "Okmulgee_Library.jpg",
    objectID: "176",
    objectName: "Image",
    pageOrder: "1",
    size: "medium"
}

Object {
    alignment: "center",
    bold: false,
    italic: false,
    objectID: "177",
    objectName: "Paragraph",
    pageOrder: "2",
    underline: false,
    value: "For more information about the Okmulgee Public Library, call (918)-756-1448."
}

Object {
    bold: false,
    italic: false,
    objectID: "179",
    objectName: "Text",
    pageOrder: "3",
    underline: false,
    value: "Or visit their website at"
}

UPDATE FROM CHROME'S Network > Headers 来自CHROME网络的更新>标题

Request URL:http://localhost:10226/AJAX%20Pages/Compute_Save_Edit_Page.cshtml
Request Method:POST
Status Code:500 Internal Server Error
Request Headersview source
Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:0
Cookie:.ASPXAUTH=AEBDE22DCB622D796F8897945434328CECAEB25BF5D24CBA9CB1C32A58D82BC5CF68F33EF2CA7012DECFE87F91C39E7471DE7C2903CE476DF8781E0B0CE862C8AF10A23CD1B52BDFBA9042290426BBD024663A2D95C02A54EBA9E98D3DE25A44415395F5CDAA1E65A0EDDC3D9598F2A7660E3376159D82986E3E4EFEB05F150D02DC788D8F0FC0D62FF8B80708D05A276789A3D54DC79F598D57D19990426F68
Host:localhost:10226
Origin:http://localhost:10226
Referer:http://localhost:10226/CMS%20Interface/EditPages/E-UtilityBilling.cshtml
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36
X-Requested-With:XMLHttpRequest
Response Headersview source
Cache-Control:private
Content-Length:5732
Content-Type:text/html; charset=utf-8
Date:Fri, 25 Oct 2013 19:00:34 GMT
Server:Microsoft-IIS/7.5
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?QzpcVXNlcnNcY3JhZGViYXVnaFxEb2N1bWVudHNcTXkgV2ViIFNpdGVzXE9rbXVsZ2VlIE9ubGluZSA0LjBcQUpBWCBQYWdlc1xDb21wdXRlX1NhdmVfRWRpdF9QYWdlLmNzaHRtbA==?=

I think you'll find your data in the Request.InputStream . 我想你会在Request.InputStream找到你的数据。 Try the following: 请尝试以下方法:

var reader = new StreamReader(Request.InputStream);
var json = reader.ReadToEnd();
var objArray= Json.Decode(json);

You will need to convert your Javascript object to JSON first by using JSON.stringify on it: 您需要首先使用JSON.stringify将Javascript对象转换为JSON:

 data: JSON.stringify(jsonArr),

Okay, I think I've finally got it. 好吧,我想我终于明白了。

I decided to try something I had tried previous to posting this question: JSON.stringify in the AJAX call (apparently jQuery doesn't automatically format the data based on contentType nor simply detecting the kind of data that it is). 我决定尝试以前尝试过发布这个问题的东西:AJAX调用中的JSON.stringify (显然jQuery不会根据contentType自动格式化数据,也不会简单地检测它的数据类型)。

The problem before was that I had NO idea that I would be able to find my data on the server-side with Request.InputStream . 之前的问题是我不知道我能用Request.InputStream在服务器端找到我的数据。 In fact, I am still not clear as to why or when data could be found in this manner or even what determines that it should be stored there as opposed to something that could be called by, say, Request.Form["objectArr"] , etc. 事实上,我仍然不清楚为什么或何时可以以这种方式找到数据,甚至是什么决定它应该存储在那里,而不是可以被Request.Form["objectArr"]调用的东西。等

So, when I tried to use JSON.stringify this time, I combined that with what Mike had posted in his answer for how to retrieve this server-side (ie, using the Request.InputStream method). 所以,当我这次尝试使用JSON.stringify时,我将其与Mike在答案中发布的内容结合起来,以了解如何检索此服务器端(即使用Request.InputStream方法)。

Once I used both (as well as, removing the identifier in the data: portion of the ajax call), I started to see and even return relevant data. 一旦我使用了两者(以及删除data:的标识符data: ajax调用的一部分),我开始看到甚至返回相关数据。

In short, here is what I have now that works... 简而言之,这就是我现在所拥有的......

The jQuery AJAX code: jQuery AJAX代码:

$.ajax({
    url: "/AJAX Pages/Compute_Save_Edit_Page.cshtml",
    async: false,
    type: "POST",
    data: JSON.stringify(jsonArr),
    success: function (response) {
        console.log(response);
    },
    error: function (jqXHR, textStatus, error) {
        alert("Oops! It appears there has been an AJAX error.\n\nPlease check the page you were attempting to edit.\n\nError Type: " + error + ".");
    }
});

And here is the server-side (C#) code that simply returns two properties of each object in the array: 这里是服务器端(C#)代码,它只返回数组中每个对象的两个属性:

@{
   Layout = "";

    if (IsAjax)
    {
        var reader = new StreamReader(Request.InputStream);
        var json = reader.ReadToEnd();
        var objectArr = Json.Decode(json);

        for (var i = 0; i < objectArr.Length; i++)
        {
@:@objectArr[i].objectName - @objectArr[i].objectID
        }
    }
    else
    {
        Context.RedirectLocal("~/");
    }
}

So, if I understand it correctly (and PLEASE correct me if I'm wrong), you CAN'T just send an array of objects to the server with AJAX. 所以,如果我理解正确(并且如果我错了纠正我),你不能只用AJAX向服务器发送一个对象数组。 In fact, I wouldn't be surprised if you couldn't even send a array, at all. 事实上,如果你根本不能发送阵列,我也不会感到惊讶。 But you CAN send a simple variable like string or int . 但你可以发送一个简单的变量像stringint So, using JSON.stringify , I am using a function that translates the array of objects into one large JSON string, reading the input stream on the other side with C#, and then using another C# method to parse the JSON string back into an array of objects, which was how I wanted the data. 所以,使用JSON.stringify ,我使用的函数将对象数组转换为一个大的JSON字符串,用C#读取另一端的输入流,然后使用另一个C#方法将JSON字符串解析回一个数组对象,这就是我想要的数据。

Thanks to all who helped me through this one, and for what it's worth, I really feel like I even learned something about the very purpose of JSON in the web environment today. 感谢所有帮助我完成这一切的人,以及它的价值,我真的觉得我甚至在今天的网络环境中学到了一些关于JSON的目的。

暂无
暂无

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

相关问题 如何在带有WebMatrix环境的C#.Net网页中实现SQL Server CE的数据库事务? - How can I go about Implementing Database transactions for SQL Server CE in a C#.Net Web-Pages w/ WebMatrix Environment? 如何使用带有WebMatrix的C#.net网页访问单个XML元素的值? - How can I access a single XML element's value using C#.net web-pages with WebMatrix? 如何在WebMatrix C#.net环境中通过jQuery AJAX调用将外部.cs文件中的特定方法作为目标? - How can I target a specific method in an external .cs file with a jQuery AJAX call in a WebMatrix C#.net environment? 如何使用 .Net (C#) 在服务器端将原始 HTML 转换为 Markdown? - How can I convert raw HTML to Markdown, server-side using .Net (C#)? 如何从asp.net-webpages中的Ajax请求获取服务器端的发布文件? - How can I get a posted file on server-side from an Ajax Request in asp.net-webpages? 使用WebMatrix Env​​ironment在C#.NET WebPages中跨范围使用GetLastInsertId()是否安全? - Is it safe to use GetLastInsertId() across scope in a C#.NET WebPages using WebMatrix Environment? 如何使用 ASP.NET 删除浏览器的缓存服务器端? - How can I remove a browser's cache server-side, using ASP.NET? 我对Web页/ WebMatrix与XSS的ASP.NET请求验证有多少信任? - How much can I trust ASP.NET Request Validation with Web Pages/WebMatrix vs. XSS? 我可以从html页面调用C#或C ++以便在本地主机上进行服务器端脚本编写/编程吗? - Can I call C#, or C++, from html pages for server-side scripting/programming on localhost? 如何从 blazor(服务器端)Web 应用程序获取访问令牌? - How do I get the access token from a blazor (server-side) web app?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM