Angular将参数从服务传递给mvc控制器

时间:2016-06-15 11:08:18

标签: angularjs asp.net-mvc

我是Angular和MVC的新手。我正在尝试将一个参数从我的视图传递给mvc控制器。删除记录后,我需要刷新视图才能看到更改。 预先感谢您的帮助。

myApp.service("deleteService", function ($rootScope, $http)
{
    this.removeRow = function (recId) {

        $http.delete("CurrentSettingsController.cs/DeleteRecord", { params: { recordId: recId } })
        .success(function (data, status, headers, config) {
            window.location.reload();
        })
        .error(function (data, status, header, config) {
        });
    }
});

myApp.controller('myController', ['$scope', 'companiesService', 'allCurrentSettingsService','deleteService',
  function ($scope, companiesService, allCurrentSettingsService, deleteService) {
      $scope.currentSettings = '';
      companiesService.getList().then(function (value) {
          $scope.currentSettings = value;

      }),
      $scope.allSettings = '';
      allCurrentSettingsService.getList().then(function (value) {
          $scope.allSettings = value;

      }),
       $scope.deleteRecordFromDB = function (recId) {
           deleteService.removeRow(recId);
       };
  }
]);

[HttpPost]
public static void DeleteRecord(int settingID)
{
    try
    {
        using (SqlConnection conn = new SqlConnection(connString))
        {
            conn.Open();
            using (SqlCommand command = new SqlCommand("DeleteCurrentRecord", conn))
            {
                command.CommandType = System.Data.CommandType.StoredProcedure;
                command.Parameters.Add("@SettingId", SqlDbType.VarChar).Value = settingID;
                command.ExecuteNonQuery();
                command.Parameters.Clear();
            }
            conn.Close();
        }
    }
    catch (Exception ex)
    {
        Console.Write(ex.ToString());
    }
}

1 个答案:

答案 0 :(得分:0)

您可以从服务返回$ http.delete,因此将返回承诺。您可以在控制器和刷新视图中添加成功回调:

myApp.service("deleteService", function ($rootScope, $http)
{
    this.removeRow = function (recId) {

        return $http.delete("CurrentSettingsController.cs/DeleteRecord", { params: { recordId: recId } });
    }
});

myApp.controller('myController', ['$scope', 'companiesService', 'allCurrentSettingsService','deleteService',
  function ($scope, companiesService, allCurrentSettingsService, deleteService) {
      $scope.currentSettings = '';
      companiesService.getList().then(function (value) {
          $scope.currentSettings = value;

      }),
      $scope.allSettings = '';
      allCurrentSettingsService.getList().then(function (value) {
          $scope.allSettings = value;

      }),
       $scope.deleteRecordFromDB = function (recId) {
           deleteService.removeRow(recId).then(
               function(success) {
                   //do refresh here
               },
               function(error) {
                   //error callback
               }
           );
       };
  }
]);