在我的代码中,我需要接收一个字符串,将其转换为C#枚举,并将该枚举传递给我的模型。代码在for循环中(未显示)。
var thisDwm = document.getElementById("dwm_" + i).value;
var urlDwm = "/KnowledgeTransfer/GetDailyWeeklyMonthlyEnum";
var response
$.ajax({
type: 'GET',
url: urlDwm,
data: { 'caseFromJS': thisDwm },
contentType: 'application/json',
success: function (thisResponse) {
response = thisResponse;
}
})
model.MainResponsibilities[i].DailyWeeklyMonthly = response;
目前,ajax命中我的C#控制器并返回正确的枚举。但是当我查看JavaScript断点时,"response“仍然是未定义的,也没有设置。如何设置可以传递给模型的C#枚举对象的响应?是否需要进行一些解析?看起来我根本没有从控制器那里收到任何东西。
无济于事的一件事是,在Chrome中,类型、数据、contentType、success和thisResponse都显示为“有引用错误未定义”。然而,Ajax仍然可以工作,至少在其他地方是这样,尽管这些其他方法也显示了这个错误。
谢谢你的帮助。
编辑:下面是我的控制器方法:
public ObjectModel.Enums.DailyWeeklyMonthly GetDailyWeeklyMonthlyEnum(string caseFromJS)
{
switch (caseFromJS){
case "Daily":
return ObjectModel.Enums.DailyWeeklyMonthly.Daily;
case "Weekly":
return ObjectModel.Enums.DailyWeeklyMonthly.Weekly;
case "Monthly":
return ObjectModel.Enums.DailyWeeklyMonthly.Monthly;
case "Yearly":
return ObjectModel.Enums.DailyWeeklyMonthly.Yearly;
default:
throw new Exception("problem with dailyWeeklyMonthly in KnowledgeTransferController");
发布于 2018-08-15 03:38:54
使用您共享的代码,如果您试图在定义变量之前使用它,您将得到response
response is not error。在您共享的代码片段中,您只能在ajax调用的success
回调方法中对其进行初始化。
记住,ajax是异步。当JavaScript框架执行这行model.MainResponsibilities[i].DailyWeeklyMonthly = response;
时,它在成功回调作用域之外,ajax调用可能仍在执行/等待来自服务器的响应,这意味着没有将任何内容设置为response
,这意味着变量response
没有初始化!
只能在success
或done
回调中访问ajax调用的响应。
$.ajax({
type: 'GET',
url: urlDwm,
data: { 'caseFromJS': thisDwm },
contentType: 'application/json',
success: function (thisResponse) {
// safe to use thisResponse in this callback method scope
console.log(thisResponse);
// Assuming model.MainResponsibilities[i] exist
model.MainResponsibilities[i].DailyWeeklyMonthly = thisResponse;
}
})
https://stackoverflow.com/questions/51848652
复制相似问题