I have a C# array which contains list of C# model:
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:
JavaScriptSerializer _serializer = new JavaScriptSerializer();
string result = _serializer.Serialize(myList);
in javascript:
jQuery.parseJSON('<%= result %>')
when Message
contains double quotation in jQuery.parseJSON method throw exception (for example Message is
hello "world"
)
Is there any way to handle this error or pass C# array to javascript array in another way??
You can use HtmlEncode function.
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 & me > them
Step 3: String is converted back from HTML.
String: you & me > them
Or you can use this method in JavaScript side.
Instead of
jQuery.parseJSON('<%= result %>')
Try simply
<%= result %>
eg it might be part of a statement like 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. This means you should be able to just directly inject it into your JavaScript code. It's already JSON, so there should be no need to parse it (as if it were a string).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.