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

3
我将为您进行翻译:

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

Angular

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

1
尝试使用 new.CustomerID 和 new.CompanyName... - ssilas777
@ssilas777 谢谢...可以了...我在想为什么我正在学习的这个教程把它标记为 new.c.customerid。 - Anonymous
啊,看起来@ssilas777比我先完成了! - skubski
@匿名者,很高兴它起作用了,我已经将它发布为答案。如果有帮助,请标记为正确答案。 - ssilas777
使用与您的域对象相同的命名约定在Angular中进行命名:customer.CustomerID,并在post请求中使用$scope.customer - jasenkoh
3个回答

3

请按照以下方式更新您的HTML:

new.c.CustomerID更改为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 () {

        });

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-->


0

您的模型似乎是

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

这不符合您的客户类映射。您应该参考new.CustomerIDnew.CompanyName。此外,我建议避免使用new关键字作为变量名。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接