简体   繁体   中英

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

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. I also tried changing JsonResult to ActionResult . Sometimes the alert says get response failed! sometimes it's Error CreateRecipe null .

Even if I put recipe.Id in an int before returning it, it still doesn't work.

Consider making the JsonResult asynchronous too using the async task and save changes to database using 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM