使用jquery ajax提交表单

本文关键字:表单 提交 ajax jquery 使用 | 更新日期: 2023-09-27 18:10:13

我正在尝试学习MVC,我想做的一件事是向我的控制器中的一个操作提交一个表单,这个操作将返回提交的数据。听起来很简单,但我已经尝试了几个小时,但没有成功。我的观点:

 @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>
}

我的控制器:

[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;
        });
    });

使用jquery ajax提交表单

仅供参考,您不需要编写任何客户端代码。

要在MVC中成功地使用ajax方法,您需要执行以下操作。将此密钥添加到web.config中的appsettings:

  <appSettings>
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>

以及包含不引人注目的ajax脚本:

<script src="/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>

然后在表单周围创建div容器,并将Html.BeginForm替换为Ajax.BeginForm

<div id="ajaxReplace">
@using (Ajax.BeginForm("BlogComment", "Blog", null, new AjaxOptions { UpdateTargetId = "ajaxReplace", OnSuccess = "doFunctionIfYouNeedTo", OnFailure = "ShowPopUpErrorIfYouWant" }))
 {
 @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>
    }
</div>

然后在你的控制器中,你会返回这样的东西:

return PartialView(ajaxComment);

这将节省您手动维护脚本的时间,并将引导您按预期使用框架。它还将帮助您进行数据注释验证和所有有趣的东西,

我希望这在某种程度上有所帮助。

试试这个:

模型

public class Comment
{
    public string CommentText { get; set; }
    public DateTime? DateCreated { get; set; }
    public long PostId { get; set; }
    public string UserName { get; set; }
}

View和js

@model SubmitMvcForWithJQueryAjax.Models.Comment
@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">
            @Html.EditorFor(m => m.UserName)
        </div>
        <div class="editor-text">
            @Html.TextAreaFor(m => m.CommentText, new { rows="6", cols="23"} )
        </div>
        <div class="editor-field">
             @Html.HiddenFor(m => m.DateCreated)        
        </div>
         <div class="editor-field">
             @Html.HiddenFor(m => m.PostId)          
        </div>
        <input type="submit" id="submit" value="Create" />
    </div>
}
<script type="text/javascript">
    $(document).ready(function () {
        $('form').submit(function () {
            var serializedForm = $(this).serialize();                       
            $.ajax({
                url: '@Url.Action("CommentForm")',
                type: "POST",                                       
                data: serializedForm,
                success: function (result) {
                    alert("success " + result.UserName);
                },
                error: function (result) {
                    alert("Failed");
                }
            });
            return false;
        });
    });
</script>

控制器

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);

    }
}

基本上,您直接传递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
        });

而不是

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;
});

在将数据发送到服务器之前,您必须将其转换为字符串。并且CCD_ 2完成该工作