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
名單? 我不知道如何做到這一點。有人可以幫忙嗎?
感謝
當前代碼發生了什麼? – Yasser