簡體   English   中英

從控制器返回的JSON對象渲染HTML到jquery ajax調用

[英]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()));
      });

這是一個小提琴樣品。

只是看着你的

&amp;lt;li&amp;gt;&amp;lt;li&amp;gt;&amp;lt;img id=&amp;quot;fbPic&amp;quot; src=&amp;quot;http://graph.facebook.com/567818188/picture&amp;quot; style=&amp;quot;display: inline; padding-right: 10px;&amp;quot;&amp;gt;&amp;lt;b&amp;gt;Bernice Zerafa&amp;lt;/b&amp;gt;&amp;lt;/li&amp;gt;&amp;lt;pre class=&amp;quot;word-wrap&amp;quot; style=&amp;quot;margin-left: 10%;&amp;quot;&amp;gt;hellooo&amp;lt;/pre&amp;gt;&amp;lt;/li&amp;gt;

我懷疑它將正確呈現它似乎不是一個有效的html,並且您不斷添加,因此您可能會使用類似

  $("#posts").append(postText);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM