[英]Angular $http post not returning Json response
Recipes/CreateRecipe was successful but return Json is not returning anything and goes to the next function which is the alert Error CreateRecipe null
Recipes / CreateRecipe成功,但是返回Json不返回任何内容,而是转到下一个函数,即警报
Error CreateRecipe null
script 脚本
$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); });
};
controller 调节器
[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);
}
I tried a lot of things like adding ModelState.IsValid
and checking if recipe.Id
is null but it wasn't. 我尝试了很多事情,例如添加
ModelState.IsValid
并检查recipe.Id
是否为null,但事实并非如此。 I also tried changing JsonResult
to ActionResult
. 我还尝试将
JsonResult
更改为ActionResult
。 Sometimes the alert says get response failed!
有时,警报提示
get response failed!
sometimes it's Error CreateRecipe null
. 有时是
Error CreateRecipe null
。
Even if I put recipe.Id
in an int before returning it, it still doesn't work. 即使我在返回它之前将
recipe.Id
放在一个int中,它仍然无法正常工作。
Consider making the JsonResult
asynchronous too using the async
task and save changes to database using await db.SaveChangesAsync();
也可以考虑使用
async
任务使JsonResult
异步,并使用await db.SaveChangesAsync();
将更改保存到数据库中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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.