[英]Render HTML from JSON object returned from controller to jquery ajax call
在ASP.NET MVC 4中,如何在加載時呈現HTML。 我將以這種形式編碼的一些html字符串保存在sql服務器數據庫中,類型為nvarchar(max)。
<li><li><img id="fbPic" src="http://graph.facebook.com/567818188/picture" style="display: inline; padding-right: 10px;"><b>Bernice Zerafa</b></li><pre class="word-wrap" style="margin-left: 10%;">hellooo</pre></li>
* 編輯: *請注意,上面的字符串未正確編碼為html,因此實際上顯示為:
<li><li><img id="fbPic" src="http://graph.facebook.com/567818188/picture" style="display: inline; padding-right: 10px;"><b>Bernice Zerafa</b></li><pre class="word-wrap" style="margin-left: 10%;">helloooo </pre></li>
現在,在頁面加載時,我將得到這些html字符串的列表,這些html字符串都是具有各種子節點的列表項,這些子節點將追加到無序列表標記中。 列表返回確定。 但是它只是按原樣顯示在頁面上,即顯示實際字符串而未呈現html。
這是我的控制器動作:
public ActionResult LoadPosts(int groupId)
{
var postedText = new List<string>();
IEnumerable<Post> posts;
using (CodeShareEntities conn = new CodeShareEntities())
{
posts = conn.Posts.Where(g => g.GroupId == groupId);
foreach (var post in posts)
{
postedText.Add(post.PostData);
}
}
return Json(new { PostedText = postedText });
}
這是我在頁面加載時對jQuery Ajax的調用。 #posts
是我的html中的空<ul>
jQuery.ajax({
type: 'POST',
url: '/Groups/LoadPosts',
data: { groupId: grpid },
success: function (postData) {
$.each(postData, function (index, postText) {
**postText = htmlUnencode(postText);**
$("#posts")[0].innerHTML = postText;
//// what can I do here instead of innerHTML to be
//// able to view the html correctly ?
//// append() and insert() methods in JQuery have the same result
//// I found something called @Html.Raw(Json.Encode()) maybe
//// this is relevant here ? How can I use this correctly ?
});
$('#posts').css('background', 'white');
},
traditional: true
});
任何幫助將不勝感激!
好像您的html是雙重編碼的。 嘗試這個
$.each(postData, function (index, postText) {
**postText = htmlUnencode(postText);**
$("#posts").append($($("<div/>").html($("<div/>").html(test).text()).text()));
});
這是一個小提琴樣品。
只是看着你的
&lt;li&gt;&lt;li&gt;&lt;img id=&quot;fbPic&quot; src=&quot;http://graph.facebook.com/567818188/picture&quot; style=&quot;display: inline; padding-right: 10px;&quot;&gt;&lt;b&gt;Bernice Zerafa&lt;/b&gt;&lt;/li&gt;&lt;pre class=&quot;word-wrap&quot; style=&quot;margin-left: 10%;&quot;&gt;hellooo&lt;/pre&gt;&lt;/li&gt;
我懷疑它將正確呈現它似乎不是一個有效的html,並且您不斷添加,因此您可能會使用類似
$("#posts").append(postText);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.