当前位置: 动力学知识库 > 问答 > 编程问答 >

html - How to write the JSON inside <span> tag in c# file?

问题描述:

StringBuilder sb = new StringBuilder();

sb.Append("<span data-date-conv='{"+"dstring"+":"+eventPage.StartDate.ToString()+","+"pattern"+":"+"P0"+"}'></span>");

Above code is not properly rendered (incorrect Format), It displays as:

<span data-date-conv="{dstring:4/25/2017 12:00:00 AM,pattern:p0}"></span>

When we write in HTML file then it displays as (correct format):

<span data-date-conv='{"dstring":"4/25/2017 12:00:00 AM","pattern":"p0"}'></span>

网友答案:

You can do it something like this

sb.Append("<span data-date-conv='{\"dstring:\"" + eventPage.StartDate.ToString() + "\",\"pattern:\"P0\"}'></span>");

Literals are how you hard-code strings into C# programs. There are two types of string literals in C# - regular string literals and verbatim string literals. In particular, " itself, \, and carriage return (CR) and line feed (LF)) need to be "escaped" to be represented in the string. To obtain a " within the string itself, you need to write "". Verbatim string literals are distinguished by having an @ before the opening quote.

Taken from Strings in C# and .NET

and thus you can also try it like

sb.Append(@"<span data-date-conv='{""dstring:""" + eventPage.StartDate.ToString() + @""",""pattern"":""P0""}'></span>");
网友答案:

When we compare the first string with the second one, the difference is the quotation marks (") that encapsulate the keys and the values. So, you can achieve what you want by manually applying them, while escaping with '\' character, to your string like this:

StringBuilder sb = new StringBuilder();
sb.Append("<span data-date-conv='{"+"\"dstring\""+":\""+eventPage.StartDate.ToString()+"\","+"\"pattern\""+":"+"\"P0\""+"}'></span>");
分享给朋友:
您可能感兴趣的文章:
随机阅读: