对控制器的Ajax调用将您带到另一个页面而不是仅返回JSON

时间:2015-01-29 15:08:01

标签: javascript jquery asp.net ajax json

我使用的是jQuery,一种模态形式 - 和MVC 5.

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

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

返回数据的行是:

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

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

Screen Shot of screen after Ajax post

我怀疑它是我的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

谢谢Mark,

完整的控制器代码是:

    [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;
});
});

1 个答案:

答案 0 :(得分:0)

这是由我按下Enter键引起的,因此触发了Form帖子 - 而不是我实际点击模态表单上的“保存”按钮。

愚蠢的错误 - 但希望有助于其他人。

谢谢,Mark