views:

35

answers:

2

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?

A: 

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);
   }
}
Alexander
That's a good point. I returned a json object but then data.message was null
griegs
Yeah looks like you may just be returning html and the Javascript is expecting a `JSON Object`...
Alexander
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
Just re-read your answer and the datatype was the problme. thanks
griegs
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`
Alexander
i made the incorrect assumption that it was what i was passing to my controller.
griegs
I also made assumptions when I was answering your question the first time. It's human nature...
Alexander
A: 

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
Sorry, the closing tokens are correct, i simply didn't copy the whole function
griegs
PostAttribute is not necessary, it'll accept all HTTP Verbs when not present...
Alexander
Does a breakpoint on `jQueryAddComment` get hit in the debugger?
jwsample
Yeah the code works fine up until the alert
griegs