Umbraco BlogComment Create Ajax

183 views Asked by At

Hello im trying to post my blog comments the function works. but the whole site refreshes inside the div, i tried playing around with the partialview in the controller but im not sure what to do can anybody here point me in the right directtion, i want div to refresh with ajax request not the whole site intro the div.

  <!-- Blog Comments -->
    <!-- Comments Form -->
    <div class="well">
        <h4>Leave a Comment:</h4>
        @if (Members.GetCurrentLoginStatus().IsLoggedIn)
        {
            using (Html.BeginUmbracoForm("CreateComment", "CommentSurface", FormMethod.Post, new { @id = "comment-form" }))
            {
                // use this where every display profile image is needed
                var user = User.Identity.Name;
                var imgUrl = Url.Content("~/media/profileimage/" + user.Replace(".", "") + ".png");

                <input name="CommentOwner" type="text" value="@Members.GetCurrentMember().Name" class="form-control hidden" readonly="readonly" />
                <input name="ownerid" type="text" value="@Members.GetCurrentMember().Id" class="form-control hidden" readonly="readonly" />
                <div class="form-group">
                    <textarea name="Message" rows="3" placeholder="Type your message here" class="form-control"></textarea>
                </div>
                <input name="profileimage" type="text" value="@imgUrl" class="hidden" readonly="readonly" />
                <button type="submit" class="btn btn-primary">Submit</button>
            }
        }
        else
        {
            <p> You are not logged in <a href="~/register">Register here</a></p>
        }
    </div>
    <hr>
    <!-- Posted Comments -->
    <div class="blog-comments">
        @Html.Partial("_BlogComments")
    </div>
    <!-- Comment -->
    @section scripts {
        <script>
            $(function () {
                // Find the form with id='well-form'
                $('#comment-form').submit(function () {
                    $.ajax({
                        url: this.action,
                        type: this.method,
                        data: $(this).serialize(),
                        success: function (data) {
                            $(".blog-comments").html(data);
                        },
                        error: function (result) {
                            alert('Comment was not successful!');
                        }
                    });
                    // return false to cancel the form post
                    // since javascript will perform it with ajax
                    return false;
                });
            });
        </script>
    }
</div>

SurfaceController:

 public class CommentSurfaceController : SurfaceController
{
    [HttpPost, ValidateInput(false)]
    public ActionResult CreateComment(CommentViewModel model)
    //public PartialViewResult CreateComment(CommentViewModel model)
    {
        if (!ModelState.IsValid)
        {
            return CurrentUmbracoPage();
        }
        var contentService = Services.ContentService;
        var newContent = contentService.CreateContent(DateTime.Now.ToShortDateString() + " " + model.CommentOwner, UmbracoContext.PageId.Value, "BlogComment");
        newContent.SetValue("CommentOwner", model.CommentOwner);
        newContent.SetValue("Message", model.Message);
        newContent.SetValue("profileimage", model.profileimage);
        newContent.SetValue("ownerid", model.ownerid);
        //Change .Save if u want to allow the content before publish
        contentService.SaveAndPublishWithStatus(newContent);
        return RedirectToCurrentUmbracoPage();
        //return PartialView("BlogComments", model);
    }

    public ActionResult DeleteComment(int commentid)
    {
        var service = ApplicationContext.Current.Services.ContentService;
        var content = service.GetById(commentid);
        service.Delete(content);
        return RedirectToCurrentUmbracoPage();

    }
}

Partial View:

@foreach (var item in Model.Content.Children().OrderByDescending(m => m.CreateDate))
{
    <div class="media">
        <a class="pull-left" href="#">
            <img class="media-object" width="64" src="@item.GetPropertyValue("profileimage")" alt="profile image">
        </a>
        <div class="media-body">
            <h4 class="media-heading">
                @item.GetPropertyValue("CommentOwner")
                <small>@item.CreateDate</small>
            </h4>
            @item.GetPropertyValue("Message")
        </div>
        @item.Id
    </div>
    if (Members.GetCurrentLoginStatus().IsLoggedIn)
    {
        if (@Members.GetCurrentMember().Id.ToString() == item.GetPropertyValue("ownerid").ToString())
        {
            @Html.ActionLink("Delete", "DeleteComment", "CommentSurface", new { commentid = item.Id }, null)
        }
        else
        {
            @*<p> not ur comment</p>*@
        }
    }
    else
    {
       //blank cant delete comment if not logged in
    }
}
1

There are 1 answers

0
dampee On BEST ANSWER

The problem is that UmbracoSurfaceController is loosing his context if you are not rendering the complete page.

If you work with ajax, you should not render out html and post this back. Only POST the data and update your layout in javascript when you get a 200 (ok) back from the server.

To do so, use the UmbracoApiController. This is a WebApi controller allowing you to send back json (or xml) serialized data.

More information about the UmbracoApiController can be found in the documentation.