0

In my ASP.Net/MVC application, I am using AngularJS to display a list of records from the database. When I update a record, it doesn't get updated in the view (html) until I refresh the page?

The view:

<tr ng-repeat="bu in bus">
  <td>{{bu.BU_Name}}</a></td>
  <td>{{bu.BU_Info}}</a></td>
  <th><a href="javascript:void(0)" ng-click="editItem(bu)">Del</a></th>
</tr>

The JS:

$scope.editItem= function (bu) {
    $http.post('/CO/DelBU', {dbunt: bu})
    .then(function (response) {
        $scope.bus = response.data;
    })
    .catch(function (e) {
        console.log("error", e);
        throw e;
    })
    .finally(function () {
        console.log("This finally block");
    });
};

The MVC controller:

[HttpPost] 
    public JsonResult DelBU(BUs dbunt)
    {
        var db = new scaleDBEntities(); 
        var burecord = db.Buses.Find(dbunt.BU_ID);
        db.Database.ExecuteSqlCommand("UPDATE dbo.BUs SET BU_Name='just a test'");
        var burecords = db.Buses.ToList();
        return Json(burecords, JsonRequestBehavior.AllowGet);
    }

So, when I click on edit, the name doesn't change on the screen unless I refresh the page! How can I fix this?

Thank you

Ahmad Shli
  • 69
  • 2
  • 10
  • Have you debugged the line: $scope.bus = response.data; to make sure you're getting the list back? – cullimorer Aug 16 '16 at 13:16
  • Well, I would say yes because the same line is used in my http.get when I first display my data from database. – Ahmad Shli Aug 16 '16 at 13:19
  • But you're not getting all your data using a POST function.... The two calls are separate from each other surely? – cullimorer Aug 16 '16 at 13:23
  • Yes, you are right – Ahmad Shli Aug 16 '16 at 13:48
  • I agree with cullimorer...something more is going on in your actual editItem/POST function that you think. You need to place a debug point and see what response.data is. – Shaggy13spe Aug 16 '16 at 14:29
  • You are right, for some reasons, the response.data did not get the updated values????? – Ahmad Shli Aug 16 '16 at 14:36
  • Not sure if this matters, it's been a while since I've done anything in C# Web API, but why do you need the JsonRequestBehavior.AllowGet on a method decorated as an HttpPost? – Shaggy13spe Aug 16 '16 at 16:42

1 Answers1

-1

i think you need to setup a watch for bus - see here for more detail:

How do I use $scope.$watch and $scope.$apply in AngularJS?

Community
  • 1
  • 1
Tom Söhne
  • 512
  • 2
  • 6
  • Tom, if possible, would you explain more how to use $watch in my code? Thanks – Ahmad Shli Aug 16 '16 at 13:41
  • Angular automatically creates the $watch by the fact that it is bound using the angular {{}} syntax – Shaggy13spe Aug 16 '16 at 14:28
  • since `` is not {{}} maybe we need to set a $watch from code? if you do not need to set a $watch by yourself `$scope.$digest();` right after `$scope.bus = response.data;` should show the updates. – Tom Söhne Aug 16 '16 at 15:24