【发布时间】:2019-09-05 12:11:15
【问题描述】:
Ajax 调用未到达控制器中的方法。我写了 ajax 调用来更新数据库中的记录。但它会返回错误的结果。怎么了?
EmployeeModel.cs
public static async Task<bool> AddOrUpdSubClassificationLevel(EmpEvaluation_SubLevels obj)
{
try
{
using (var entities = new WebPortalEntities())
{
entities.EmpEvaluation_SubLevels.AddOrUpdate(obj);
await entities.SaveChangesAsync();
}
return true;
}
catch (Exception ex)
{
CommonHelper.WriteError($"AddSubClassificationLevel ERROR: {JsonConvert.SerializeObject(ex)}");
}
return false;
}
EmployeeController.cs
[HttpPost]
public async Task<JsonResult> CreateSubClassification(EmpEvaluation_SubLevels obj)
{
obj.AuthorId = UserID;
obj.CreatedDate = DateTime.Now;
var result = await EmployeeModel.AddOrUpdSubClassificationLevel(obj);
return Json(result, JsonRequestBehavior.AllowGet);
}
Ajax 调用自身
$('#submit-edited-sublevel').on('click',
function() {
if ($('#idOfSubPost').val()) {
showGlobalLoadingWrapper();
var editedclassificationsublevel = {
Id: parseInt($('#idOfSubPost').val()),
EmpEvaluationLevelsId: $('#idOfLevel').val(),
Name: $('#edited-sublevel-name').val(),
AuthorId: 1,
CreatedDate: new Date()
}
$.ajax({
type: "POST",
contentType: 'application/json, charset=utf-8',
url: "/Employee/CreateSubClassification",
data: JSON.stringify(editedclassificationsublevel),
success: function(data) {
$("#editSubClassificationModal").modal("hide");
hideGlobalLoadingWrapper();
getClassificators();
},
error: function(error) {
hideGlobalLoadingWrapper();
console.log(error);
}
});
}
});
预期结果为真。我认为它必须来自 EmployeeModel.cs 。这是用于更新提供的数据的功能。这也应该在 db 中提交。
【问题讨论】:
-
检查 AJAX 调用中的editedclassificationsublevel 是否与控制器中的 EmpEvaluation_SubLevels 完全匹配
-
尝试使用这个 - `data: { EmpEvaluation_SubLevels: JSON.stringify(editedclassificationsublevel) }, `
标签: ajax asp.net-mvc entity-framework asp.net-ajax c#-3.0