Recipes / CreateRecipe成功但返回Json没有返回任何内容并转到下一个警告Error CreateRecipe null
脚本
$scope.createRecipe = function (recipe) {
$http({
method: 'POST',
url: '/Recipes/CreateRecipe',
data: JSON.stringify(recipe)
}).then(function (response) {
if (response!=null) {
$scope.recipeID = response.data;
alert($scope.recipeID)
}
else {
alert("get response failed! " + response.data)
}
}, function (response) { alert('Error CreateRecipe '+response.data); });
};
控制器
[HttpPost]
public JsonResult CreateRecipe([Bind(Include = "Id,Name")] Recipe vm)
{
Recipe recipe = new Recipe();
recipe.Name = vm.Name;
db.Recipes.Add(recipe);
db.SaveChanges();
return Json(recipe.Id, JsonRequestBehavior.AllowGet);
}
我尝试了很多内容,例如添加ModelState.IsValid
并检查recipe.Id
是否为空,但事实并非如此。我也尝试将JsonResult
更改为ActionResult
。有时,警报会显示get response failed!
,有时会Error CreateRecipe null
。
即使我在返回之前将recipe.Id
放入int中,它仍然无效。
答案 0 :(得分:1)
考虑使用JsonResult
任务使async
异步,并使用await db.SaveChangesAsync();
将更改保存到数据库。
public async Task<JsonResult> CreateRecipe([Bind(Include = "Id,Name")] Recipe vm)
{
int recipeId = -1;
if(vm != null) {
Recipe recipe = new Recipe();
recipe.Name = vm.Name;
db.Recipes.Add(recipe);
await db.SaveChangesAsync();
recipeId = recipe.Id;
if(recipeId > 0) {
return Json(recipeId, JsonRequestBehavior.AllowGet);
}
}
return Json(false, JsonRequestBehavior.AllowGet);
}