I have created a simple ajax mvc code snippet. The owl idea is to post message from a textarea box to the controller through ajax and update and element on the page with result of the ajax request. But unfortunately the update part of the code is not working.
Problem :- The function (..){} part of the ajax does not execute.
This is the html code
<div id="comments"></div>
<form method="post" action=@Url.Action("postComment") id="jaidoform">
<div>Comment: @Html.TextArea("Comment", new {cols=5, rows = 10 })</div>
<button id="submit">Submit</button>
</form>
The ajax code
$('#jaidoform').submit(function (event) {
event.preventDefault();
var data = $(this).serialize();
var url = $(this).attr('action');
alert(url);
$.post(url, data, function (response) {
$('#comments').append(response);
});
});
This is the controller handling the ajax process
public class AjaxController : Controller
{
//This container is going to hold a list of comment
private static List<string> comments = new List<string>();
//This is going to perform an ajax post from a form to the database
[HttpPost]
public ActionResult postComment(string comment){
comments.Add(comment);
if(Request.IsAjaxRequest())
{
ViewBag.Comment = comment; //This is going to send a comment alone to the view and it would send it as a partial view
return PartialView();
}
return RedirectToAction("index");
}
}