LL Janneh
LL Janneh

Reputation: 180

I am getting error on Post method of MVC controller using AngularJS

I am using angualarJS and asp.net web API but my code always breaks on post request in the asp.net controller and this is the error I got

An exception of type 'System.ArgumentNullException' occurred in EntityFramework.dll but was not handled in user code Additional information: Value cannot be null.

this is the MVC method

 // POST: api/ProductCategory
    public HttpResponseMessage Post(ProductCategory pcate)
    {
        if (ModelState.IsValid)
        {

            this.pcat.pcategory.Add(pcate);
            this.pcat.SaveChanges();
            return Request.CreateResponse(HttpStatusCode.Created, pcate);
        }
        else
        {
            return Request.CreateResponse(HttpStatusCode.BadRequest, pcate);
        }
    }

this is the angularJS controller

  var appcat = angular.module("PharmacyControllers", ['ngRoute']);

appcat.controller("createController", ['$scope', '$http', '$location', function ($scope, $http, $location)
{
    $scope.submit = function()
    {
        //converting the object to JSON
        var obj = {

            Name: $scope.Name
        };
        //alert(obj);
        $http.post("/api/productCategory/", this.obj).success(function (data) {
            $location.path('/list');
        }).error(function (data) {

            $scope.error = "An error has occured while adding product Category! " + data.ExceptionMessage;
        });
    }

}]);

thanks in advanced

Upvotes: 1

Views: 675

Answers (2)

DaveB
DaveB

Reputation: 9530

Try changing from:

$http.post("/api/productCategory/", this.obj).success(function (data) {

to:

$http.post("/api/productCategory/", { pcate: obj }).success(function (data) {

Upvotes: 0

Lex
Lex

Reputation: 7194

You are creating a local variable obj here:

var obj = {
    Name: $scope.Name
};

But then you are trying to post this.obj to your API:

$http.post("/api/productCategory/", this.obj)

Either create the this.obj instead of the var obj or pass obj instead of this.obj on your post.

Upvotes: 1

Related Questions