[英]MVC $.ajax call never executes controller action on Edit but works on Add
我正在使用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解決您的問題,對響應字符串進行編碼,在js腳本中添加@Html.Raw(data)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.