MVC $.ajax 调用从不对编辑执行控制器操作,但在添加时有效

MVC $.ajax call never executes controller action on Edit but works on Add

本文关键字:操作 添加 有效 控制器 执行 调用 ajax 编辑 MVC      更新时间:2023-09-26

我正在使用MVC5并调用$.ajax根据客户选择填充我的"细分"下拉列表(某些细分属于某些客户)。当我转到我的"添加"视图时,以下 JavaScript 工作正常。但是,当我转到"编辑"视图并运行完全相同的脚本时,它不起作用。

我在 getSubdivisions() 控制器方法中放置了一个断点,它在添加页面上工作正常。但是,当我在"编辑"页面上时,$.ajax 调用永远不会命中控制器操作。$.ajax 调用只是失败。问题出在哪里?

我在"添加"和"编辑"视图的末尾都有以下行:

@Scripts.Render("~/bundles/schedule")

~/bundles/schedule 文件在 BundleConfig 中定义.cs:

bundles.Add(new ScriptBundle("~/bundles/schedule").Include("~/Scripts/mainsys/schedule.js"));

这是我的JavaScript...

try {
    $('#CustomerID').change(function () {
        getSubdivisions();
    });
    getSubdivisions();
}
catch (ex) {
    alert(ex.message);
}
function getSubdivisions() {
    custId = $('#CustomerID').val();
    // remove all of the current options from the list
    $('#SubdivisionID').empty();
    // send request for list of subdivisions
    var jqxhr = $.ajax({
        url: './getSubdivisions',
        type: 'POST',
        data: '{ customerId: ' + custId.toString() + ' }',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        cache: false,
        async: true
    });
    // received list of models...
    jqxhr.done(function (data) {
        if (data == null) return;
        try {
            var ddl = $('#SubdivisionID');
            // add each item to DDL
            $.each(data, function (index, value) {
                ddl.append($('<option></option>', { value: data[index].SubdivisionID }).html(data[index].SubdivisionName))
            });
        }
        catch (ex) {
            alert("Done, but with errors!'n" + ex.message);
        }
    });
    // failed to retrieve data
    jqxhr.error(function (result, errorText, thrownError) {
        alert("Error! Failed to retrieve models! " + errorText + "'n" + thrownError);
    });
}

这是我的控制器方法...

    [HttpPost]
    public string getSubdivisions(int customerId)
    {
        try
        {
            if (customerId <= 0) return null;
            List<s84_Subdivision_Short> lst = s84_Subdivision.listItemsShort(customerId);
            string s = JsonConvert.SerializeObject(lst);
            return s;
        }
        catch (Exception)
        {
            return "";
        }
    }

jqxhr.error...

errorText is "parsererror" and thrownError is "Invalid character."

更新:在Firefox中,错误显示为"JSON.parse:意外字符"

我更改了 $.ajax 调用,以便它不使用相对路径...现在一切正常。

使用 Html.Raw 来解决您的问题,响应字符串已编码,添加 @Html.Raw(data)在 js 脚本中