将对象从AngularJS传递到ASP.NET MVC控制器

时间:2015-08-20 13:31:08

标签: asp.net-mvc angularjs

我正在尝试将一些数据从AngularJS传递给我的MVC控制器,但是客户对象在MVC控制器上始终为null。我错过了什么?

        $scope.new = {};

        $scope.AddCustomer = function () {
        $http.post('/Customer/SaveCustomer', $scope.new).success(function () {

        });
    }

HTML

  <input class="form-control" type="text" placeholder="CustomerID" ng-model="new.c.CustomerID" />
  <input class="form-control" type="text" placeholder="CompanyName" ng-model="new.c.CompanyName" />
  <button type="button" class="btn btn-primary" ng-click="AddCustomer()">Save</button>

C#

 [HttpPost]
 public void SaveCustomer(Customer customer)
 {
     ....
 }

 public class Customer
 {
    public string CustomerID { get; set; }

    public string CompanyName { get; set; }
 }

3 个答案:

答案 0 :(得分:3)

像这样更新您的HTML:

new.CustomerID更改为<input class="form-control" type="text" placeholder="CustomerID" ng-model="new.CustomerID" /> <input class="form-control" type="text" placeholder="CompanyName" ng-model="new.CompanyName" />

$http.post('/Customer/SaveCustomer', $scope.new).success(function () {

        });

现在这将有效

char

答案 1 :(得分:1)

首先介意javascript对象中的驼峰案例

$scope.new = {
  customerID: '',
  companyName: ''
}; 

$scope.AddCustomer = function() {
    $http.post('/Customer/SaveCustomer', $scope.new).success(function() {});
<!--check the changes in ng-model-->
<input class="form-control" type="text" placeholder="CustomerID" ng-model="new.customerID" />
<input class="form-control" type="text" placeholder="CompanyName" ng-model="new.companyName" />
<button type="button" class="btn btn-primary" ng-click="AddCustomer()">Save</button>



<!--Best of Luck-->

答案 2 :(得分:0)

你的模特似乎是

new = {
  c : {
     CustomerID : '',
     CompanyName : ''
  }
}

哪个没有映射到您的Customer类。您应该参考new.CustomerIDnew.CompanyName。此外,我会避免使用new关键字作为变量名。