【发布时间】:2014-05-03 00:49:29
【问题描述】:
将基本的ActionResult 转换为JSON 对象并将它们呈现在PartialView 中时,最好的方法是什么?我的目标是修改应用程序,以便在页面请求时仅将 db 中的 cmets 页面呈现到一种数据服务类型,该服务更新PartialView 以添加任何可能已经发布的传入 cmets最后一页请求。我认为我正在寻找的解决方案将以json 格式使用OData,然后使用knockout.js 绑定该数据,但不确定。
这里是控制器ActionResult,它将一个IEnumerable对象列表从存储库返回到PartialView:
[ChildActionOnly]
public ActionResult GetCommentsById(int AId = 0)
{
if (AId == 0)
return HttpNotFound();
return PartialView("_CommentsPartial",
_unitOfWork.ArticleRepository.GetCommentsByArticleId(AId));
}
这是PartialView 的sn-p 以保持简短:
@model IEnumerable<BlogSite.Models.Comment>
@using BlogSite.Helpers;
<ul id="comments-list">
@{
foreach (var comment in Model)
{
<!--Grabs Parent Comment and then all replies w/ParentCommentId b4 grabs new Parent Comment -->
if (comment.isRoot && comment.ParentCommentId == null)
{
<!-- Comment -->
int counter = 0; foreach (var c in Model) { if (c.ParentCommentId == comment.CommentId) { counter += 1; } }
<li id="@comment.CommentId" itemscope itemtype="http://schema.org/UserComments" class="comment-container" tabindex="@comment.CommentId">
然后我从详细信息视图中调用它:
<div id="comments-panel" class="panel-box">
<div class="show-comments"><div id="upNdown"></div><span id="showNhide">Show Comments</span></div><br /> <br />
<div id="comments-partial" style="display:none;">
@Html.Action("AddComment", "Comment", new { AId = Model.ArticleId })
@Html.Action("GetCommentsById", "Article", new { AId = Model.ArticleId })
</div>
</div>
我怎样才能使这种转换尽可能轻松?提前致谢!
【问题讨论】:
-
我在您的示例中没有看到 JSON...不确定您的目标是什么...
-
我想将 ActionResult 返回的对象 convert 转换为 JsonResult 中的 JSON 对象(我认为),然后在实际视图中展示这些更改。
-
我仍然不知道您想要什么...考虑显示所需 HTML 的小样本(包括该 JSON 部分)。
-
我已经使用 $.ajax 调用了我的 create/update/delete ActionResult 方法,效果很好,但是从您的回复中,我想知道将所有 crud 操作内容类型转换为 json 是否值得麻烦。我不明白我应该如何请求 json 中的对象,然后在视图中呈现它们(例如:data[0].Id、data[0].ParentCommentId 等)而不是当前格式(即:(foreach (模型中的 var 注释)
-
检查this question - 可能对您有所帮助...我仍然不明白您为什么希望/在哪里显示 JSON...祝您好运。
标签: c# asp.net-mvc json razor asp.net-mvc-partialview