从JQuery调用调用控制器方法会发生两次并返回错误?

时间:2012-06-10 05:07:41

标签: asp.net-mvc asp.net-mvc-3 jquery asp.net-ajax

大家好我以前发过类似的帖子,但那是另一个,现在我的Jquery代码面临一个奇怪而奇怪的问题。在这里,我使用Jquery调用控制器方法,但它调用了两次,因此可能会导致我的数据库中有两个条目。这是我在JQuery中编写的内容

<script type="text/javascript">
    $('#btnSubmit').click(function () {
        var instructorUrl = '@Url.Action("ApplyToBecomeInstructor", "InstructorApplication")';
        var currentUser = '@Model.CurrentUserId';
        var user = [];
        var educationList = [];
        var experience = $('#Experience').val();
        var isWilling = $('#WillingToTravel').is(":checked");
        $('#editorRows .editorRow').each(function () {
            var education = {
                UniversityOrCollege: $(this).find('.university').val(),
                AreaOfStudy: $(this).find('.area').val(),
                Degree: $(this).find('.degree').val(),
                YearReceived: $(this).find('.year').val()
            }
            educationList.push(education);
        });
        var applicationFromView = {
            EducationalBackgrounds: educationList,
            CurrentUserId: currentUser,
            Experience: experience,
            WillingToTravel: isWilling
        }
        $.ajax({
            type: 'POST',
            url: instructorUrl,
            dataType: 'JSON',
            async: false,
            data: JSON.stringify(applicationFromView),
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                return false;
            },
            error: function (data) {
            alert(xhr.status);
            alert(thrownError);
            alert(xhr.responseText);
                return false;
            }
        });
    });
</script>

我的控制器操作如下所示

[HttpPost]
public ActionResult ApplyToBecomeInstructor(InstructorApplicationViewModel applicationFromView)
{
    Student thisStudent = this.db.Students.Where(o => o.StudentID == applicationFromView.CurrentUserId).FirstOrDefault();
    List<PaulSchool.Models.EducationalBackground> educationList = new List<EducationalBackground>();
    foreach (var educate in applicationFromView.EducationalBackgrounds)
    {
        var education = new Models.EducationalBackground
        {
            YearReceived = educate.YearReceived,
            Degree = educate.Degree,
            AreaOfStudy = educate.AreaOfStudy,
            UniversityOrCollege = educate.UniversityOrCollege
        };
        educationList.Add(education);
    }
    var instructorApplication = new InstructorApplication
    {
        BasicInfoGatheredFromProfile = thisStudent,
        Experience = applicationFromView.Experience,
        EducationalBackground = new List<Models.EducationalBackground>(),
        WillingToTravel = applicationFromView.WillingToTravel
    };
    instructorApplication.EducationalBackground.AddRange(educationList);
    this.db.InstructorApplication.Add(instructorApplication);
    this.db.SaveChanges();
    return this.Redirect("Index");
}

显示的错误消息是JSON解析错误..但它让我感到困惑。 我真的很想知道为什么会这样,有人可以看看并帮助我吗?

2 个答案:

答案 0 :(得分:1)

这就是您的代码所做的事情:

$('#btnSubmit').click(function () { // attach a click handler for the button.
...
...
// Look for elements inside the button... 
UniversityOrCollege: $(this).find('.university').val(), 

click更改为submit

$('#formId').submit(function (e) { 
    ...
    // Now "this" is the form - not the button.
    // Look for elements inside the <form>
    UniversityOrCollege: $(this).find('.university').val(), 
    // Prevent the default form submition
    return false // Or: e.preventDefault();

另一个提示:使用jQuery serialize函数。

答案 1 :(得分:0)

每按一次按钮,

$('#btnSubmit').click()将会触发。用户通常会双击按钮,即使它只需要单击一下,或者如果您没有任何迹象表明发生了某些事情,他们就会感到不耐烦并再次点击它。您需要某种方法来确定是否已提出请求。有这样的方法来做这个客户端和服务器端。最简单的客户端方法是禁用该按钮以防止多次点击:

$('#btnSubmit').click(function () {
    // Disable the button so it can't be clicked twice accidentally
    $('#btnSubmit').attr('disabled', 'disabled');
    //...
    $.ajax({
        //...
        complete: function() {
            // Make sure we re-enable the button on success or failure so it can be used again
            $('#btnSubmit').removeAttr('disabled');
        }
    });
});