2012-12-21 25 views
0

我對此很陌生,不知道它是如何工作的。使用Ajax困境更新視圖中的HTML標記

在我看來,我有一個foreach的局部視圖,列出了該新聞文章的所有新聞評論。

我有一個文本區,有一個post按鈕,用戶可以在這裏提交關於這篇新聞文章的更多評論。

新消息文章必須附加到列表中,而不是執行location.reload。我被告知使用AJAX,而不是JSON

這裏是我的控制器:

[HttpGet] 
[NoCache] 
public ActionResult SetCommentOnNews(int newsId, string newsComment) ?? 
{ 
    var currentUser = ZincService.GetUserForId(CurrentUser.UserId); 
    ZincService.NewsService.SetCommentOnNews(newsId, newsComment, currentUser.UserId); 
    return Json(new { success = true }, JsonRequestBehavior.AllowGet); ?? 
} 


<div class="news-comment-content" id="news-comment-content"> 
     <% if (Model.Results != null) { 
     foreach (var newsItem in Model.Results.NewsComments) %> 
     <% { %> 
     <% Html.RenderPartial("~/Views/Home/SetCommentOnNews.ascx", newsItem); %> 
     <% } %> 
</div> 

我的部分:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Zinc.Web.Areas.News.ViewModels.Home.NewsCommentsViewModel>" %> //this also not right 

<div class="news-post-list-item"> 
    <div class="news-post-user-info-wrapper"> 
    <div class="avatar"> 
     <img width="52" height="52" alt="Avatar" src="/ThemeFiles/Base/images/User/user-avatar.png"/> 
    </div> 
    <div class="who-and-when-box"> 
     <%: newsItem.CommentDate %> 
     <br /> 
     <br /> 
     <%: ViewBag.UserName %> 
    </div>   
    <div class="news-comment"><%: newsItem.NewsComment %></div> 
    <div class="clear"></div> 
    </div>  
    <div class="clear"></div> 
</div> 

<div class="header"> 
    <h3> 
     Leave a comment 
    </h3> 
</div> 
<div> 
    <textarea id="textareaforreply" rows="3" cols="160"></textarea> 
</div> 
<div> 
    <a href="javascript:PostNewsComment(<%: Model.News.NewsId %>);" class="button" id="post_button">Post</a>  
</div> 

<script type="text/javascript"> 
function PostNewsComment(newsId) { 
    $("post-button").click(function() { 
     var jqxhr = $.getJSON("<%= //Url.Action("SetCommentOnNews", "Home", new { area = "News" }) %>?newsId=" + newsId + "&newsComment=" + $("#textareaforreply").text(), function (data) { 
    if (data.success) { 
     alert($("#textareaforreply").text()); 
     $('#news-comment').append($("#textareaforreply").text()); 
    } 
    }); 
} 
</script> 

以上JS是我的,必須注入HTML使用AJAX名單? 我不知道如何做到這一點。有人可以幫忙嗎?

感謝

+0

當前代碼發生了什麼? – Yasser

回答

0

要注入HTML到使用AJAX的清單,我會用Knockoutjs with templates代替的部分景色。敲除可用於在瀏覽器中呈現信息。渲染服務器端的視圖,這與AJAX不兼容。

當你說「我被告知使用AJAX而不是JSON」時,你是什麼意思。 AJAX使用JSON作爲序列化通過網絡發送的數據的方法。你指的是jQuery方法AJAX的getJSON的getJSON只是圍繞AJAX方法,該方法將其配置專門使用HTTP GET動詞檢索JSON的包裝。要麼能夠正常工作,但阿賈克斯給你更多的配置請求的控制權。

相關問題