我在使用AngularJS的MVC控制器的Post方法上遇到错误

时间:2016-03-25 23:14:36

标签: c# asp.net angularjs asp.net-web-api

我正在使用angualarJS和asp.net web API,但我的代码总是在asp.net控制器中的post请求中断,这是我得到的错误

  

发生了'System.ArgumentNullException'类型的异常   EntityFramework.dll但未在用户代码中处理   信息:值不能为空。

这是MVC方法

 // 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);
        }
    }

这是angularJS控制器

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

}]);

先谢谢

2 个答案:

答案 0 :(得分:1)

您在此处创建了一个本地变量obj

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

但是,您尝试将this.obj发布到您的API:

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

在帖子上创建this.obj代替var obj或传递obj而不是this.obj

答案 1 :(得分:0)

尝试更改:

 float timer = 0;
 bool timerCheck = false;
 float timerThreshold = 1000; // value you want to wait

 void Update()
 {
     if(timerCheck)
     {
        timer += Time.deltaTime;
     }
     if (timer > timerThreshold)
     {
        timer = 0;
        GameObject gObj = ...; // get player game object using GameObject.FindWithTag for example

        if (gObj.CompareTag("enemy") && hajs.hp > 0)
        {
            hajs.hp = hajs.hp - loss_hp;
        }
     }
 }

 void OnCollisionEnter2D(Collider2D col)
 {
    timerCheck = true;
 }

 void OnCollisionExit2D(Collider2D col)
 {
    timerCheck = false;
 }

为:

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