【问题标题】:How to serialize forms and post using jQuery Ajax如何使用 jQuery Ajax 序列化表单和发布
【发布时间】:2015-02-25 07:19:09
【问题描述】:

我正在尝试从我的数据库中删除记录...... 这就是我的表单的样子.........

@using (Html.BeginForm("RemoveDoctor", "Doctor", FormMethod.Post, new { @id = "form" }))
{
    @Html.AntiForgeryToken()
    @Html.HiddenFor(model => model.Id)
    @Html.HiddenFor(model => model.Name)
    <div class="form-actions no-color">
        <input type="submit" value="Delete" class="btn btn-default" id="submit" /> |

    </div>
}

我正在尝试从视图中获取这些记录并传递给我的控制器 Action 方法..........................我正在尝试序列化此表单并将其发送到该操作方法,如下所示......

var jsonObj = $('#form').serialize();

它序列化表单让我的 Ajax POST 函数不会运行该结果...... 它只是给了我一个错误!!!!........我只需要将序列化值传递给我的 Action 方法............ ....这就是我的脚本的样子.....................

$('#submit').click(function () {

     var jsonObj = $('#form').serialize();
     alert(jsonObj);

     $.ajax({
           type: "POST",
           url: '../Doctor/RemoveDoctor',
           data: JSON.stringify({ "doctor": jsonObj }),
           success: function (data) {
                 alert(data.Message);
           },
           error: function () {
                  alert("Error!!!");
           }
      });
      return false;

});

这就是我的操作方法的样子............

  public ActionResult RemoveDoctor(DoctorModel doctor)
  {
      bool confirmationResult = doctorManager.RemoveDoctor(doctor.Id);
      string displayMessage = string.Empty;
      if (confirmationResult == true)
           displayMessage = "You have successfully removed your record!!";
      else
           displayMessage = "Error!! Some Thing Went Wrong, Please Try Again!!";

      return Json(new { Message = displayMessage });

  }

我正在尝试将这个“displayMessage”发送到我的 jQuery 代码........请给我一个如何解决这个问题的想法......谢谢!!!!!!

【问题讨论】:

    标签: javascript jquery ajax jquery-mobile serialization


    【解决方案1】:

    试试这个

     $.ajax({
               type: "POST",
               url: '../Doctor/RemoveDoctor',
               data: $('#form').serialize(),
               success: function (data) {
                     alert(data.Message);
               },
               error: function () {
                      alert("Error!!!");
               }
          });
    

    它将序列化您的表单。

    仅使用$('#form').serialize() 进行序列化。

    编辑

    如果您不想刷新页面,则应使用type="button" 而不是type="submit"

    你也应该这样做

    [HttpPost]
    public ActionResult RemoveDoctor(DoctorModel doctor)
      {
          //...................
          return Json(new { Message = displayMessage } , JsonRequestBehavior.AllowGet);
    
      }
    

    并将 ajax 错误函数更改为此(用于获取错误)

    error: function(jqXHR, textStatus, errorThrown)
    {
      alert("Error: "+errorThrown+" , Please try again");   
    }
    

    【讨论】:

    猜你喜欢
    • 2021-08-15
    • 2011-11-12
    • 2011-05-31
    • 1970-01-01
    • 1970-01-01
    • 2011-08-09
    • 1970-01-01
    • 2018-05-04
    • 2014-07-23
    相关资源
    最近更新 更多