最近用asp.net結合Extjs開發一個新聞發布功能的模組,發現Extjs的grid無法顯示帶Html標記的新聞內容,百思不得其解,在FF和IE下沒有任何錯誤,而且,FF調試下,新聞內容資料已經取出來了,而且json格式也是正確的,但就是不顯示。
很奇怪!
最終經過反覆研究,發現一個細節,我們從網頁直接拷貝新聞,然後粘貼到Extjs的htmleditor裡,發布,會含有很多的\r \n 標記,只要卻掉就OK了,而且\是逸出字元,要做處理,不然同樣不顯示的。
json格式雖然簡單,但是一定要組織好,不然就不會顯示了。
好說解決方案:
很簡單,只要將新聞內容欄位做一個replace就可以了。看我的IList2json的方法:
public string ToJsonString<T>(string jsonName, IList IL)
{
StringBuilder Json = new StringBuilder();
Json.Append("{" + jsonName + ":[");
if (IL.Count > 0)
{
for (int i = 0; i < IL.Count; i++)
{
T obj = Activator.CreateInstance<T>();
Type type = obj.GetType();
PropertyInfo[] pis = type.GetProperties();
Json.Append("{");
for (int j = 0; j < pis.Length; j++)
{
string ILValue = "";
if (pis[j].GetValue(IL[i], null) != null)
{
ILValue = pis[j].GetValue(IL[i], null).ToString().Replace("'", "\"").Replace("\r", "").Replace("\n", "").Replace("\\
',"////");//關鍵就是這裡,替換掉敏感字元就OK了
}
Json.Append("'" + pis[j].Name.ToString() + "':'" + ILValue + "'");
if (j < pis.Length - 1)
{
Json.Append(",");
}
}
Json.Append("}");
if (i < IL.Count - 1)
{
Json.Append(",");
}
}
}
Json.Append("]}");
return Json.ToString();
}