0

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.

5
  • can you post what you see inside console.log(response.data); Commented Jan 10, 2018 at 3:59
  • @Sajeetharan Create Recipe http post doesn't return a response and just goes to the next function which is the error alert and the response there is null Commented Jan 10, 2018 at 4:43
  • When you return Json(recipe.Id, ..), does recipe.Id have a value? Commented Jan 10, 2018 at 7:38
  • @Sajal Yes, it has a value when I check in the controller. Commented Jan 10, 2018 at 7:49
  • You should consider making the json result async too, when you open the db layer, the thread probably doesn't wait for recipe.Id and returns a null/undefined value back to angularjs. Commented Jan 10, 2018 at 7:53

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.