簡體   English   中英

Ajax jQuery並不總是在Controller上執行操作

[英]Ajax jQuery not always executes action on Controller

我在ASP.NET MVC 3(C#)中制作了下面的Controller方法,該方法返回PartialView:

public ActionResult InsertEmail(long idPerson)
    {
        PersonEmailViewModel mail = new PersonEmailViewModel();
        mail.email.Person_idPerson = idPerson;
        return PartialView(mail);
    }

我需要在提交表單上執行的方法是:

[HttpPost]
    public ActionResult InsertNewEmail(PersonEmail mail)
    {
        mail.idPersonEmail = mail.Insert(mail);
        return Json(mail);
    }

我的partialView包含以下代碼:

@model PlatformLib_MySql.BLL.Person.PersonEmailViewModel
<form action="" id="frmNewEmail" method="post">
<div>
E-mail: @(Html.TextBoxFor(m => m.email.email))
@(Html.HiddenFor(m => m.email.Person_idPerson))
<input type="submit" value="Insert" id="btnSubmitMailInsert" />
<input type="button" value="Cancel" id="btnCancelMailInsert" />
</div>
</form>

在我的JS文件中,我在#btnSubmitMailInsert按鈕上運行以下代碼:

jQuery("#btnSubmitMailInsert").click(function () {
submitNewEmail();
window.location.reload();
});
function submitNewEmail() {
event.preventDefault();
var mail = {
    email: jQuery("#frmNewEmail #email_email").val(),
    Person_idPerson: jQuery("#frmNewEmail #email_Person_idPerson").val()
};

var request = jQuery.ajax({
    url: '/Person/InsertNewEmail',
    data: mail,
    type: 'POST',
    dataType: 'json',
    cache: false
});

request.done(function (msg) {
    console.log(msg);
});

request.fail(function (msg) {
    console.log(msg);
});
}

我的問題集中在Ajax請求上。 我很少能做出“快樂的方式”,在單擊提交時,該事件在jQuery上激活,調用方法“ submitNewEmail()”,該方法調用Ajax,在控制器上執行該方法並成功通過。 但是,並非如此...它總是以失敗返回,不是因為控制器方法返回了錯誤,而是因為ajax無法正常運行,即使在其中插入了斷點(在VS2010上),也不會在控制器上執行該方法。 在我發布的此JS代碼中,嘗試替代解決此問題,但未成功。 原始代碼是:

    jQuery.ajax({
    url: '/Person/InsertNewEmail',
    data: mail,
    type: 'POST',
    dataType: 'json',
    cache: false,
    success: function (result) {
        debugger;
        jQuery("#tblEmail").append("<tr><td>Email inserido</td></tr>");
    },
    error: function () {
        debugger;
        alert("Erro ao inserir e-mail.");
    }
});

我暫時保留了“ console.log(msg)”,只是為了解決此問題。

你們中的某人可以告訴我發生了什么,還是指出我的錯誤在哪里?

我發現了問題。 一切都很好,但是一些細節破壞了代碼:window.location.reload();

我對代碼進行了一些更改,如下所示:

    jQuery.ajax({
    url: '/Person/InsertNewEmail',
    data: mail,
    type: 'POST',
    dataType: 'json',
    cache: false
}).done(function (data) {
    // Do something
});

另一種方法也是正確的,唯一相關的更改是:

jQuery("#btnSubmitMailInsert").click(function () {
event.preventDefault();
submitNewEmail();
// window.location.reload // -> Commented for testing and everything worked fine.
});

感謝您嘗試幫助我。 這對我有很大幫助。

暫無
暫無

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

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