使用jquery ajax提交表单
我正在尝试学习MVC,我想要做的事情就是在我的控制器中向一个动作提交一个表单,这个动作将返回提交的数据。 听起来很简单,但我已经尝试了几个小时而没有任何成功。 我的看法:
@using (Html.BeginForm("BlogComment","Blog")) { @Html.ValidationSummary(true) User Name: }
我的控制器:
[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); }
和我的js:
$(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; }); });
基本上你直接传递javascript对象文字。 因此,在将数据传递给控制器之前,它必须是JSON
格式(因为您已经指定了application / json。请参阅$ .ajax调用)。
那么,你缺少JSON.stringify()
data: JSON.stringify({ PostId: $('.postid').val(), UserName: $('#username').val(), DateCreated: new Date(), CommentText: $('#comment').val() }),
要么
var someObj = { PostId: $('.postid').val(), UserName: $('#username').val(), DateCreated: new Date(), CommentText: $('#comment').val() }; $.ajax({ /// your other code data: JSON.stringify(someObj), // your rest of the code });
您不需要编写任何客户端代码来执行此操作,仅供参考。
要在MVC中成功使用ajax方法,您需要执行以下操作。 将此密钥添加到web.config中的appsettings:
除了包含不引人注目的ajax脚本:
然后在表单周围创建div容器,并用Ajax.BeginForm替换Html.BeginForm
@using (Ajax.BeginForm("BlogComment", "Blog", null, new AjaxOptions { UpdateTargetId = "ajaxReplace", OnSuccess = "doFunctionIfYouNeedTo", OnFailure = "ShowPopUpErrorIfYouWant" })) { @Html.ValidationSummary(true) User Name: }
然后在您的控制器中,您将返回以下内容:
return PartialView(ajaxComment);
这将节省您维护脚本以手动执行此操作,并将使您按预期使用框架。 它还将帮助您进行数据注释validation以及随之而来的所有多汁内容,
我希望这在某种程度上有所帮助。
试试这个:
该模型
public class Comment { public string CommentText { get; set; } public DateTime? DateCreated { get; set; } public long PostId { get; set; } public string UserName { get; set; } }
视图和js
@model SubmitMvcForWithJQueryAjax.Models.Comment @using (Html.BeginForm("BlogComment","Blog")) { @Html.ValidationSummary(true) User Name: @Html.EditorFor(m => m.UserName) @Html.TextAreaFor(m => m.CommentText, new { rows="6", cols="23"} ) @Html.HiddenFor(m => m.DateCreated) @Html.HiddenFor(m => m.PostId) }
控制器
public class CommentController : Controller { // // GET: /Comment/ public ActionResult Index() { return View(new Comment()); } [HttpPost] public ActionResult CommentForm(Comment comment) { Comment ajaxComment = new Comment(); ajaxComment.CommentText = comment.UserName; ajaxComment.DateCreated = comment.DateCreated ?? DateTime.Now; 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); } }
代替
data: { PostId: $('.postid').val(), UserName: $('#username').val(), DateCreated: new Date(), CommentText: $('#comment').val() },
尝试
$('form').submit(function () { var obj = { PostId: $('.postid').val(), UserName: $('#username').val(), DateCreated: new Date(), CommentText: $('#comment').val() }; $.ajax({ ..., data: JSON.stringify(obj), ..., }); return false; });
在将数据发送到服务器之前,必须将数据转换为字符串。 和JSON.stringify
完成这项工作