3

I'm trying to pass some data to my MVC controller from AngularJS but the Customer object is always null on the MVC controller. What am I missing?

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; } } 
5
  • 1
    Try new.CustomerID and new.CompanyName...
    – ssilas777
    CommentedAug 20, 2015 at 13:33
  • @ssilas777 thanks...That worked...I wonder why this tutorial I'm going through has it labeled as new.c.customerid
    – Anonymous
    CommentedAug 20, 2015 at 13:35
  • Ah, seems @ssilas777 beat me to it!
    – skubski
    CommentedAug 20, 2015 at 13:36
  • @Anonymous, Glad it worked, I have posted it as answer..Please mark as correct anwser if it helped.
    – ssilas777
    CommentedAug 20, 2015 at 13:38
  • use same naming convention on angular as your domain object. customer.CustomerID and do post $scope.customer
    – jasenkoh
    CommentedAug 20, 2015 at 13:41

3 Answers 3

3

Update your HTML like this :

Change new.c.CustomerID to 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" /> 

Now this will work

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

    First mind the camel case in javascript object

    $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

      Your model seems to be

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

      Which doesn't map to your Customer class. You should refer to new.CustomerID and new.CompanyName. Futhermore I would avoid using the new keyword as variable name.

        Start asking to get answers

        Find the answer to your question by asking.

        Ask question

        Explore related questions

        See similar questions with these tags.