1

I am stuck saving multiple rows I pushed in "$scope.arr" to my SQL Server database. I have my code below and it works fine but when I click on "Save To DB" button after adding/pushing some entries by pressing "Add Person" button, it passes a row with null values to SQL Server database. Please guide me where I am doing the mistake:

I also heard about using angular.forEach loop but I am confused using that too.

I have my model class "TestModel.cs" here:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace TestProj.Models
{
    public class TestModel
    {
        public int ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}

My MVC Controller named TestController's Add method here:

[HttpPost]
public string AddPerson(TestModel test)
            using (TestContext db = new TestContext())
            {
                if (test != null)
                {
                    db.TestModels.Add(test);
                    db.SaveChanges();
                    return "Successful";
                }
                else
                {
                    return "Failed";
                }
            }
        }

My AngularJS script here:

var app = angular.module("TestApp", []);

app.controller("TestCtrl", function ($scope, TestService) {

    $scope.arr = [];

    $scope.addPerson = function () {
        var myobj = {
            FirstName: $scope.firstname,
            LastName: $scope.lastname
        }
        $scope.arr.push(myobj);
    };

    $scope.savePerson = function () {
        var TestData = TestService.AddPer($scope.arr);
        TestData.then(function (msg) {
            alert(msg.data);
        }, function () {
            alert('Error In Adding Person');
        });
    };

});

app.service("TestService", function ($http) {

    this.AddPer = function (person) {
        var response = $http({
            method: "post",
            url: "/Test/AddPerson",
            data: JSON.stringify(person),
            dataType: "json",
        });
        console.log(response);
        return response;
    }
});

And my Index.cshtml file here:

<div ng-controller="TestCtrl">
    <form>
        FirstName: <input class="form-control" ng-model="firstname" /><br />
        LastName: <input class="form-control" ng-model="lastname" /><br />
        <button class="btn btn-success" ng-click="addPerson()">Add Person</button>
        <button class="btn btn-success" ng-click="savePerson()">Save To DB</button>

        <table class="table table-bordered">
            <tr>
                <th>S. No</th>
                <th>First Name</th>
                <th>Last Name</th>
            </tr>
            <tr ng-repeat="a in arr">
                <td>{{$index+1}}</td>
                <td>{{a.FirstName}}</td>
                <td>{{a.LastName}}</td>
            </tr>
        </table>
    </form>
</div>

<script src="~/Scripts/MyAngular/Module.js"></script>

Your help will be appreciated. Thanks!

2 Answers 2

1

Then server side action should expect collection of TestModel, you could us List there. If you [FromBody] before parameter, you don't need to stringify data before posting it to server.

Code

[HttpPost]
public string AddPerson([FromBody] List<TestModel> test)
  using(TestContext db = new TestContext()) {
    test.forEach(t=> {
      if (t != null) {
          db.TestModels.Add(t);
          return "Successful";
      } else {
          return "Failed";
      }
    });
    db.SaveChanges(); //save context at the end, when no error occurs
  }
}
Sign up to request clarification or add additional context in comments.

5 Comments

This technique did not work but a very close method to this worked where I did this: [HttpPost] public void AddPerson(List<TestModel> test) { using (TestContext db = new TestContext()) { foreach(var t in test) { if (t != null) { db.TestModels.Add(t); Console.WriteLine("Success"); } } db.SaveChanges(); //save context at the end, when no error occurs } }
You only changed .forEach lambda to simple forEach.. I can't see other changes.. I think my answer is correct..even though you wrote yours :D
Your answer was perfect @Pankaj Parkar. But my Visual Studio wasn't loading assemblies I don't know why :/ Thanks anyway for helping :)
I upvoted and accepted it now. Sorry for being late! :D
@RehanSiddiqui no problem. Glad to help you. Thanks :-)
1

The problem was in my Server Side Code i.e, my C# controller, this method worked:

[HttpPost]
        public void AddPerson(List<TestModel> test)
        {
            using (TestContext db = new TestContext())
            {
                foreach(var t in test) 
                {
                    if (t != null)
                    {
                        db.TestModels.Add(t);
                        Console.WriteLine("Success");
                    }
                }
                db.SaveChanges(); //save context at the end, when no error occurs
            }
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.