Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a PartialView from $.Ajax Post

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?

like image 461
griegs Avatar asked Aug 16 '10 01:08

griegs


People also ask

How can I return a partial call from ajax?

So, let's create one simple MVC application and try to return a partial from controller and display it using jQuery AJAX. Here is our small controller class. The controller class is just a stub and not doing anything great. It contains a testPartial() function that will return a partial view as a result.

Can we return a value from ajax call?

You can't return "true" until the ajax requests has not finished because it's asynchron as you mentioned. So the function is leaved before the ajax request has finished.

How do I return from ajax?

Ajax is a very well known method for loading the content of a Web page without manually refreshing it. But the letter “A” in Ajax means asynchronous, meaning that you need to have a callback function that will return the results.


1 Answers

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);
   }
}
like image 120
Alex Avatar answered Sep 18 '22 07:09

Alex