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?
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.
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.
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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With