1

What is the best approach to take when converting a basic ActionResult to JSON objects and rendering them in a PartialView? My objective is to modify the application so that instead of the page rendering only the comments in the db at the time of the page request to a type of data service that updates thePartialView to add any incoming comments that may have been posted since the last page request. I think the solution I am looking for will use OData in json format and then bind that data using knockout.js, but not sure.

Here is the Controller ActionResult which returns an IEnumerable list of objects from the repository to a PartialView:

        [ChildActionOnly]
        public ActionResult GetCommentsById(int AId = 0)
        {

            if (AId == 0)
                return HttpNotFound();

            return PartialView("_CommentsPartial",  
            _unitOfWork.ArticleRepository.GetCommentsByArticleId(AId));
        }

Here is a snippet of the PartialView to keep things short:

@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">

Then I call it from the Details view:

<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>

How can I make this conversion as painless as possible? Thanks in advance!

yardpenalty.com
  • 1,244
  • 2
  • 17
  • 32
  • I don't JSON see anywhere in your sample... Not sure what your goal is... – Alexei Levenkov May 03 '14 at 01:01
  • I want to **convert** the objects returned from the ActionResult into JSON objects in a JsonResult (I think) and then have these changes demonstrated in an actual view. – yardpenalty.com May 03 '14 at 01:27
  • I still have no idea what your want... consider showing tiny sample of desired HTML (which includes that JSON part). – Alexei Levenkov May 03 '14 at 01:29
  • I already have my create/update/delete ActionResult methods being called using $.ajax which works fine, but from your response I am wondering if converting all the crud actions content-type to json is even worth the trouble. I don't get how I should request the objects in json and then render them in the view (eg: data[0].Id, data[0].ParentCommentId, etc..) instead of current format (ie: (foreach(var comment in Model) – yardpenalty.com May 03 '14 at 02:02
  • 1
    Check [this question](http://stackoverflow.com/questions/1056121/how-to-create-json-string-in-c-sharp) out - may help you... I still don't get why/where do you want JSON to show up... Good luck. – Alexei Levenkov May 03 '14 at 02:06
  • I may have just posted a bad question. It seems that I am attempting use json where a simple $.get would work just fine. My intention was that I could increase performance by rendering all of the page comments from a json array object after the page loads similar to how Yahoo! comments are rendered. After looking over your suggestion, I think a simple $.get would suffice. Maybe I can work json into this question like having a small popup div when new comments are posted similar to [cbssports.com](http://www.cbssports.com/). Thanks for the help. – yardpenalty.com May 03 '14 at 02:31

1 Answers1

1

I think I gather from your question that the controller already did its work and that you simply want to "consume" the data output from it as if it were an AJAX request using the same js code. You can do this fairly easily by just serializing the data in the model using the Newtonsoft Json.NET api and extensions provided by Forloop.HtmlHelpers. These can be installed as nuget packages if you haven't already.

First, you would place this in your partial view
Note: If you don't want to install the Newtonsoft package you can replace JsonConvert.SerializeObject with the System.Web.Helpers method Json.Encode

@{
    using (var context = Html.BeginScriptContext())
    {
        Html.AddScriptBlock("var jsonData=" + JsonConvert.SerializeObject(Model) + ";");
    }
}

Then in your layout page, to ensure that your script block is rendered at the appropriate time, add this call to Html.RenderScripts

@Scripts.Render("~/bundles/jquery")
@*Add any other dependency scripts*@

@Html.RenderScripts()

@RenderSection("scripts", required: false)

This is why you need the Forloop.HtmlHelpers package, these extension methods help mitigate out-of-order script code getting rendered in the partial view before jQuery or anything else has started up.

Hope that helps

Bron Davies
  • 5,930
  • 3
  • 30
  • 41
  • Yes yes! Thank you. I was going to put Ajax.Request in an edit, but I found myself a little discouraged as I thought I may be way off based. Alexei had pointed me to a great question which I was considering the Newtonsoft api. Once again, yes! I will look into that helper package as well and show my work upon completion as I don't want to be pegged as just another bad question user-person. – yardpenalty.com May 03 '14 at 06:31
  • My initial intention was that if I could make this type of modification I could eventually use knockout.js to bind the json data using a DataService as explained [here](http://msdn.microsoft.com/en-us/magazine/jj133816.aspx). – yardpenalty.com May 03 '14 at 07:12
  • No problem. I've seen bad questions and questions that are just hard to understand. In the future, it helps if you supply what you have and where you want to get to (the ideal output you've envisioned) This makes your problem easier to understand and solve and less likely to get down-voted. – Bron Davies May 03 '14 at 21:59