Angular $ http帖子没有返回Json响应

时间:2018-01-10 01:50:54

标签: angularjs json asp.net-mvc entity-framework controller

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中,它仍然无效。

1 个答案:

答案 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);
}