簡體   English   中英

如何使用jQuery Ajax序列化表單並發布

[英]How to serialize forms and post using jQuery Ajax

我正在嘗試從數據庫中刪除記錄……這就是我的表單的樣子…………

@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代碼中........請讓我知道如何解決此問題.......謝謝!!!

嘗試這個

 $.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");   
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM