简体   繁体   English

如何在不转换为json的情况下使用C#数组到javascript数组?

[英]How to use C# array to javascript array without converting to json?

I have a C# array which contains list of C# model: 我有一个C#数组,其中包含C#模型的列表:

public class AlertInfo
{
    public long Id { get; set; }
    public string Message { get; set; }
}

I converted array of C# to json and used in javascript like below: 我将C#数组转换为json,并在javascript中使用,如下所示:

JavaScriptSerializer _serializer = new JavaScriptSerializer();
string result = _serializer.Serialize(myList);

in javascript: 在javascript中:

jQuery.parseJSON('<%= result %>')

when Message contains double quotation in jQuery.parseJSON method throw exception (for example Message is Message在jQuery.parseJSON方法中包含双引号时引发异常(例如Message是

hello "world" 你好,世界”

)

Is there any way to handle this error or pass C# array to javascript array in another way?? 有什么方法可以处理此错误,也可以通过其他方式将C#数组传递给javascript数组?

You can use HtmlEncode function. 您可以使用HtmlEncode函数。

Example code: 示例代码:

string text = "you & me > them"; // 1

 // Replace > with >
 string htmlEncoded =Server.HtmlEncode(text); // 2

 // Now has the > again.
 string original =Server.HtmlDecode(htmlEncoded); // 3

The Output: 输出:

Step 1: Before encoding has occurred.
String: you & me > them

Step 2: The string is encoded for HTML.
String: you &amp; me &gt; them

Step 3: String is converted back from HTML.
String: you & me > them

Or you can use this method in JavaScript side. 或者,您可以在JavaScript端使用此方法。

Instead of 代替

jQuery.parseJSON('<%= result %>')

Try simply 简单尝试

<%= result %>

eg it might be part of a statement like var myVariable = <%= result %> 例如,它可能是var myVariable = <%= result %>类的语句的一部分

Since the serialiser already produced JSON, and JSON is JavaScript Object Notation, it is directly interpretable as a JavaScript variable when it's part of a JavaScript statement. 由于序列化程序已经生成了JSON,并且JSON是JavaScript Object Notation,因此当它是JavaScript语句的一部分时,可以直接将其解释为JavaScript变量。 This means you should be able to just directly inject it into your JavaScript code. 这意味着您应该能够直接将其注入到您的JavaScript代码中。 It's already JSON, so there should be no need to parse it (as if it were a string). 它已经是JSON,因此不需要解析它(就好像它是一个字符串一样)。

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

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