我正在使用 MVC5 并调用 $.ajax 根据客户选择填充我的“细分”下拉列表(某些细分属于某些客户)。当我转到我的添加视图时,以下 JavaScript 工作正常。但是,当我转到编辑视图并运行完全相同的脚本时,它不起作用。
我在 getSubdivisions() 控制器方法中放置了一个断点,它在 Add 页面上运行良好。但是,当我在编辑页面上时,$.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:意外字符”