21

I have the following code;

        $.ajax({
            url: "/Home/jQueryAddComment",
            type: "POST",
            dataType: "json",
            data: json,
            contentType: 'application/json; charset=utf-8',
            success: function(data){ 
                //var message = data.Message; 
                alert(data);
                $('.CommentSection').html(data);
            }

And in my controller;

    [ValidateInput(false)]
    public ActionResult jQueryAddComment(Comment comment)
    {
        CommentSection commentSection = new CommentSection();

        //ya da - ya da 
        // fill the commentsection object with data

        //then
        return PartialView("CommentSection", commentSection);

    }

However, when I get back to the page the success alert doesn't happen. Can anyone see the flaw in this logic?

griegs
  • 22,624
  • 33
  • 128
  • 205

2 Answers2

33

Your expecting JSON in the .Ajax POST, but in the ActionMethod your returning a PartialView?

Try:

$.ajax({
   url: "/Home/jQueryAddComment",
   type: "POST",
   dataType: "html",
   data: json,
   success: function(data){ 
      //var message = data.Message; 
      alert(data);
      $('.CommentSection').html(data);
   }
}
Alex
  • 34,899
  • 5
  • 77
  • 90
  • That's a good point. I returned a json object but then data.message was null – griegs Aug 16 '10 at 02:02
  • Yeah looks like you may just be returning html and the Javascript is expecting a `JSON Object`... – Alex Aug 16 '10 at 02:04
  • If I return Json and then alert this window.alert(data) I get Object. So how do I now get the html within the object. – griegs Aug 16 '10 at 02:12
  • Just re-read your answer and the datatype was the problme. thanks – griegs Aug 16 '10 at 02:15
  • You have to change `dataType:json` to `dataType:"html"` in your script as what your returning from the `ActionMethod` is HTML not a `JSON Object` – Alex Aug 16 '10 at 02:16
  • i made the incorrect assumption that it was what i was passing to my controller. – griegs Aug 16 '10 at 02:24
  • I also made assumptions when I was answering your question the first time. It's human nature... – Alex Aug 16 '10 at 02:46
1

Unless it was copied over wrong it appears you are missing some closing tokens.

       $.ajax({
        url: "/Home/jQueryAddComment",
        type: "POST",
        dataType: "json",
        data: json,
        contentType: 'application/json; charset=utf-8',
        success: function(data){ 
            //var message = data.Message; 
            alert(data);
            $('.CommentSection').html(data);
            } //<-- added close for anonymous function
        }); //<--added close/semicolon for ajax function

Also, you are POSTing but it your action doesn't appear to have the [Post] attribute. When you run this in the debugger does a breakpoint on your action get hit?

jwsample
  • 2,401
  • 19
  • 18