【问题标题】:Ajax call to controller takes you to another page instead of just returning JSON对控制器的 Ajax 调用将您带到另一个页面,而不仅仅是返回 JSON
【发布时间】:2015-01-29 15:08:01
【问题描述】:

我正在使用 jQuery,一种模态表单 - 和 MVC 5。

当我在模态框上单击“确定”时,下面的 javascript 应该对“Companies/Createa”控制器进行 ajax 调用。

这很好,代码运行并更新了我的数据库 - 但是,当将 JSON 数据返回到 ajax 调用时,浏览器页面显示 JSON 数据 - 而不是遵循 javascript 代码并添加新值到下拉列表。

返回数据的行是:

return Json(new { Company = dbCompany, Error = string.Empty });

任何人都可以看到为什么控制器不只是将 JSON 发送到 ajax 请求,而不是发送到以下内容:

我怀疑这是我的 javascript 代码 - 但我正在尝试按照 asp.net 网站上的示例:http://www.asp.net/mvc/overview/older-versions/working-with-the-dropdownlist-box-and-jquery/adding-a-new-category-to-the-dropdownlist-using-jquery-ui

谢谢你,马克

完整的控制器代码是:

    [HttpPost]
    public ActionResult Createa([Bind(Include = "CompanyId,CompanyName")] Company company)
    {
        try
        {
            if (ModelState.IsValid)
            {
                db.Company.Add(company);
                db.SaveChanges();

                var dbCompany = db.Company.Where(g => g.CompanyName == company.CompanyName).SingleOrDefault();
                // **** Following line executes and sends back JSON data ****
                return Json(new { Company = dbCompany, Error = string.Empty });
            }
            else
            {
                string errMsg = "Something failed, probably validation";
                var er = ModelState.Values.FirstOrDefault();
                if (er != null && er.Value != null && !String.IsNullOrEmpty(er.Value.AttemptedValue))
                    errMsg = "\"" + er.Value.AttemptedValue + "\" Does not validate";
                return Json(new { Error = errMsg });
            }
        }
        catch (InvalidOperationException ioex)
        {
            if (ioex.Message.Contains("Sequence contains more than one element"))
                return Json(new { Error = "Value provided exists in DB, enter a unique value" });
            return Json(new { Error = "Internal Error with input provided" });
        }
        catch (Exception ex)
        {
            return Json(new { Error = "Internal Error with input provided" });
        }
    }

调用控制器的jQuery/Javascript是:

$(function () {
$('#companyDialog').dialog({
    autoOpen: false,
    width: 500,
    height: 250,
    modal: true,
    title: 'Add Company',
    buttons: {
        'Save': function () {
            alert("Save pressed");  // This alert never shows
            var createCompanyForm = $('#createCompanyForm');
            if (createCompanyForm.valid()) {
                $.post(createCompanyForm.attr('action'), createCompanyForm.serialize(), function (data) {
                    if (data.Error != '') {
                        alert("Error noted: " + data.Error);
                    }
                    else {
                        // Add the new company to the dropdown list and select it
                        $('#CompanyId').append(
                                $('<option></option>')
                                    .val(data.Company.CompanyId)
                                    .html(data.Company.CompanyName)
                                    .prop('selected', true)  // Selects the new Company in the DropDown LB
                            );
                        $('#companyDialog').dialog('close');
                    }
                });
            }
        },
        'Cancel': function () {
            $(this).dialog('close');
        }
    }
});

$('#companyAddLink').click(function () {
    var createFormUrl = $(this).attr('href');
    //alert(createFormUrl);
    $('#companyDialog').html('')
    .load(createFormUrl, function () {
        // The createCompanyForm is loaded on the fly using jQuery load. 
        // In order to have client validation working it is necessary to tell the 
        // jQuery.validator to parse the newly added content
        jQuery.validator.unobtrusive.parse('#createCompanyForm');
        $('#companyDialog').dialog('open');
    });
    //alert("finished click function");
    return false;
});
});

【问题讨论】:

  • 到达你提供的$.post回调函数了吗?
  • 嗨 Vijay - 你刚刚帮我解决了这个问题(或者至少让我意识到不是点击保存按钮不起作用 - 是我在输入模式框时按 Enter ,而不是单击“保存”按钮 - 从而触发表单 Post,而不是通过 jQuery 代码以编程方式)!干杯!

标签: javascript jquery asp.net ajax json


【解决方案1】:

这是由于我按下了 Enter 键,从而触发了表单发布 - 而不是我实际点击了模态表单上的“保存”按钮。

愚蠢的错误 - 但希望对其他人有所帮助。

谢谢,马克

【讨论】:

  • 你不认为这是一个潜在的错误。您应该将输入键处理为模型弹出窗口的默认操作(即保存):D
  • 是的,我同意 - 认为我必须添加一些代码来捕获它,并确保输入触发按钮单击,而不是表单发布。有点痛苦,但我现在要去谷歌了 :) 干杯维杰
猜你喜欢
  • 2013-07-19
  • 2021-10-24
  • 2018-08-06
  • 2013-11-30
  • 2015-05-21
  • 1970-01-01
  • 1970-01-01
  • 2016-03-26
  • 2013-12-29
相关资源
最近更新 更多