views:

81

answers:

1

I have the following code:

<div id="comments">
    <h2>
        Comments</h2>
    <div id="comment">
    </div>
    <% foreach (var comment in this.Model.Topic.TopicComments.OrderBy(tc => tc.CreatedDate).Reverse())
       { %>
    <% this.Html.RenderPartial("TopicComment", comment); %>
    <% } %>
    <fieldset>
        <% using (Ajax.BeginForm("AddComment", "Topic", new { id = this.Model.Topic.TopicId },
                new AjaxOptions { UpdateTargetId = "comment", OnSuccess = "animateTopicComment" }))
           { %>
        <%= Html.TextArea("Body", string.Empty, new { @class = "wmd-ignore" })%>
        <input type="submit" value="Add Comment" />
        <% } %>
    </fieldset>
</div>

<script type="text/javascript">

    function animateTopicComment() {
        $("#comment").fadeOut(0, function() {
            $('#comment').fadeIn("slow");
        });
        $("#Body").val("");
    }

</script>

What I am trying to do is whenever the user adds a comment I would like the comment to fade in. This almost works ... save for the following issue:

If I keep adding comments, whatever was in the comment DIV is overridden. If I don't use any of the jQuery animations the new comments appear correctly.

+1  A: 

Could it have something to do with you fadeing out all elements that have an id of comment first? Can you try to remove the fadeout and only have the fadein?

failing that, you could give the new comment a unique id and fade only that in.

Also, what's in your partial view for the comments? can you provide that code?

EDIT

Just had a bit more of a think. I've implemented the same sort of thing as you and the way I did it was to do a jQuery postback which returned html via RenderPartial. I then simply [appended] that html to the end of the div containing the comments and faded it in.

Would that be appropriate in your circumstance?

griegs
That would work ... silly question ... how would you append it?
mattruma
It's not a silly question. You'd use the append keyword. So let's assume you have a div and it has a class name of "MyContent". All you need to do is take the html returned from your jQuery post and say something like $('.MyContent').append(html); The doco for it is here http://docs.jquery.com/Manipulation/append
griegs
So instead of using the UpdateTargetId in my Ajax call, I would do all this in a separate function?
mattruma
Unsure what you mean. The process that i use is 1) allow the user to enter a comment in a box. 2) on click of a button do a jQuery call back to the controller. 3) grab the new comment and add it to the database. 4) return RenderPartial*("partialName", newComment) 5) append that comment to the end of my comment list.
griegs