Tôi đang cố gắng tìm hiểu MVC và một trong những điều tôi muốn làm là gửi biểu mẫu đến một hành động trong bộ điều khiển của tôi và hành động này sẽ trả về dữ liệu đã gửi. Nghe có vẻ đơn giản nhưng tôi đã cố gắng hàng giờ mà không thành công. quan điểm của tôi:Gửi mẫu với jquery ajax
@using (Html.BeginForm("BlogComment","Blog"))
{
@Html.ValidationSummary(true)
<legend class="AddAComment">Add a comment</legend>
<div class="commentformwrapper">
<div class="editor-text">
<span class="editor-label">User Name:</span>
</div>
<div class="editor-text">
<input type="text" id="username" />
</div>
<div class="editor-text">
<textarea id="comment" rows="6" cols="23"></textarea>
</div>
<div class="editor-field">
<input type="hidden" id="hiddendate" />
</div>
<input type="submit" id="submit" value="Create" />
</div>
}
điều khiển của tôi:
[HttpPost]
public ActionResult CommentForm(Comment comment)
{
Comment ajaxComment = new Comment();
ajaxComment.CommentText = comment.UserName;
ajaxComment.DateCreated = comment.DateCreated;
ajaxComment.PostId = comment.PostId;
ajaxComment.UserName = comment.UserName;
mRep.Add(ajaxComment);
uow.Save();
//Get all the comments for the given post id
return Json(ajaxComment);
}
và js của tôi:
$(document).ready(function() {
$('form').submit(function() {
$.ajax({
url: '@Url.Action("CommentForm")',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: {
PostId: $('.postid').val(),
UserName: $('#username').val(),
DateCreated: new Date(),
CommentText: $('#comment').val()
},
success: function (result) {
alert("success " + result.UserName);
},
error: function (result) {
alert("Failed");
}
});
return false;
});
});
vấn đề của bạn là gì? Điều gì không hoạt động? – nemesv
bạn đang thiếu JSON.stringify() –