Служба AngularJS не вызывает контроллер для получения обновленных данных после операции CRUD

0

Я начинаю работу в AngularJS и пытаюсь создать экран ввода основных данных, где верхняя часть содержит поля формы и нижнюю часть, содержащую таблицу (GridView) для отображения всех основных записей. Сетка показывает все данные, когда я изначально запускаю приложение. Если я добавляю/редактирую любые новые/старые записи, обновленные данные не отражаются в gridview. (т.е.) Если я добавлю новую запись, она будет сохраняться в БД через сервис, но не отражается в GridView. Даже если я перемещаюсь по меню, также не отображаю обновленные данные в сетке. Но если я нажимаю Ctrl + F5, он показывает обновленные данные в Grid. Alsp Если я закрою браузер и запустил приложение, то обновленные записи отображаются в Gridview. Ниже мой код. Пожалуйста, помогите.. Спасибо.!

Index.cshtml

<div class="row">
    <div class="col-md-12">
        <h3 class="page-header">
            Component Master
        </h3>
        <div class="col-md-12">
            <div class="alert alert-dismissible alert-danger" ng-show="ComponentForm.$invalid && submitted">
                <button type="button" class="close" aria-hidden="true" data-dismiss="alert">
                    &times;</button>
                <p ng-show="ComponentForm.ComponentName.$error.required && (ComponentForm.ComponentName.$dirty || submitted)">
                    - Component Name is required.</p>
                <p ng-show="ComponentForm.ComponentName.$error.minlength && (ComponentForm.ComponentName.$dirty || submitted)">
                    - Component Name should be minimum 5 char long.</p>
                <p ng-show="ComponentForm.Language.$error.required && (ComponentForm.Language.$dirty || submitted)">
                    - Language Selection is required.</p>
            </div>
        </div>
        <div class="col-md-12">
            <div class="panel panel-success">
                <div class="panel-heading">
                    <h3 class="panel-title">
                        Panel success</h3>
                </div>
                <div class="panel-body">
                    <div class="row">
                        <div class="col-lg-12">
                            <!-- FORM : YOU CAN DISABLE, HTML5 VALIDATION BY USING "novalidate" ATTRIBUTE-->
                            <form name="ComponentForm" class="form-inline" novalidate>
                            <!-- COMPONENT NAME -->
                            <div class="form-group" ng-class="{ 'has-error' : ComponentForm.ComponentName.$invalid && (ComponentForm.ComponentName.$dirty || submitted) }"
                                style="margin: 10px;">
                                <label style="margin-right: 10px;">
                                    Component Name</label>
                                <input type="text" name="ComponentName" ng-model="ComponentModel.ComponentName" class="form-control"
                                    placeholder="Component Name..." ng-minlength="5" ng-required="true" />
                                <input type="hidden" data-ng-model="ComponentModel.ComponentID" />
                                <input type="hidden" data-ng-model="ComponentModel.IsActive" />
                                <input type="hidden" data-ng-model="UserID" />
                            </div>
                            <!-- LANGUAGE -->
                            <div class="form-group" style="margin: 10px;" ng-class="{ 'has-error' : ComponentForm.Language.$invalid && (ComponentForm.Language.$dirty || submitted) }">
                                <label style="margin-right: 10px;">
                                    Language</label>
                                <select name="Language" data-ng-model="ComponentModel.Language" class="form-control"
                                    ng-required="true">
                                    <option value="" title="Select">Select</option>
                                    <option value="English" title="English">English</option>
                                    <option value="Spanish" title="Spanish">Spanish</option>
                                </select>
                            </div>
                            <!-- ng-disabled FOR ENABLING AND DISABLING SUBMIT BUTTON -->
                            <!-- SAVE BUTTON -->
                            @*<button type="submit" class="btn btn-info" ng-disabled="ComponentForm.$invalid" value="Add">Add</button>*@
                            <button type="submit" class="btn btn-primary" ng-click="SaveComponent(ComponentModel);"
                                ng-value="Add">
                                Add
                            </button>
                            <button type="submit" class="btn btn-warning" ng-click="ClearComponent();" value="Clear">
                                Clear
                            </button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-12">
            <table class="table table-striped table-bordered table-hover">
                <thead>
                    <tr class="success">
                        <th class="text-center">
                            ComponentID
                        </th>
                        <th class="text-center">
                            Component Name
                        </th>
                        <th class="text-center">
                            Language
                        </th>
                        <th class="text-center">
                            IsActive
                        </th>
                        <th class="text-center">
                            Last Modified By
                        </th>
                        <th class="text-center">
                            Last Modified Date
                        </th>
                        <th class="text-center">
                            Action
                        </th>
                    </tr>
                    <tr style="height: 250px; border: 2px solid #ecf0f1;" data-ng-show="ShowEmptyRow">
                        <th colspan="7" class="text-center" style="vertical-align: middle;">
                            <label class="control-label">
                                No Records Found.</label>
                        </th>
                    </tr>
                </thead>
                <tbody>
                    <tr data-ng-repeat="Component in ComponentMaster" data-ng-show="!ShowEmptyRow" ng-class="{'danger':!Component.IsActive}">
                        <td style="vertical-align: middle; text-align: center;">
                            {{ Component.ComponentID}}
                        </td>
                        <td style="vertical-align: middle;">
                            {{ Component.ComponentName}}
                        </td>
                        <td style="vertical-align: middle;">
                            {{ Component.Language}}
                        </td>
                        <td style="vertical-align: middle; text-align: center;">
                            <div class="checkbox">
                                <label>
                                    <input type="checkbox" disabled="disabled" ng-checked="Component.IsActive" /></label>
                            </div>
                        </td>
                        <td style="vertical-align: middle;">
                            {{ Component.ModifiedBy}}
                        </td>
                        <td style="vertical-align: middle; text-align: center;">
                            {{ Component.ModifiedDate}}
                        </td>
                        <th style="vertical-align: middle; text-align: center;">
                            <span class="btn btn-info btn-sm" ng-show="Component.IsActive" ng-click="EditComponent(Component.ComponentID);">
                                Edit</span> <span class="btn btn-danger btn-sm" ng-show="Component.IsActive" ng-click="ActivateDeActivateComponent(Component.ComponentID,false,ComponentModel.ModifiedBy);">
                                    Delete</span> <span class="btn btn-info btn-sm" ng-show="!Component.IsActive" ng-click="ActivateDeActivateComponent(Component.ComponentID,true,ComponentModel.ModifiedBy);">
                                        Activate</span>
                        </th>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

Угловой сценарий:

 var AngularApp = angular.module("AngularApp", ['ngRoute']);

AngularApp.controller("ConfigurationController", ['$scope', 'ConfigurationService', function ($scope, ConfigurationService) {
    $scope.ComponentMaster = [];
    GetComponentMasterDetails();

    /*-------------  Save Component       ---------------- */
    // When i click Save btn - executing this function. control comes here...
    $scope.SaveComponent = function (ComponentModel) {
        $scope.submitted = true;
        if ($scope.ComponentForm.$valid) {

            ComponentModel.ModifiedBy = $scope.UserID;
            // control comes here... & Calling method "SaveComponentMaster" inside ConfigurationService & returned execution message
            var Msg = ConfigurationService.SaveComponentMaster(ComponentModel);
            Msg.then(function (response) {
                if (response.data != "") {
                    alert(response.data);
                }
                else {
                    // After Saved into DB showing below alert message.
                    alert("Data Saved Successfully.");      
                    // Calling below method to get the updated records from DB            
                    GetComponentMasterDetails();
                }
            }, function (error) {
                alert(error.data);
            });
        }
        else {
            alert("Please correct errors!");
        }
    }
    /**----------------------------------------------------- */
    // Below method is calling...
    function GetComponentMasterDetails() {
        // Call moves to ConfigurationService Service method...
        var ComponentMaster = ConfigurationService.GetComponentMasterDetails();
        ComponentMaster.then(function (response) {
            if (response.data != "") {
                // This service call returning the old data only.
                // Updated/Added entry details not reflecting in the returned object. 
                // This is the reason why it is showing old records only in the Grid.
                $scope.ShowEmptyRow = false;
                $scope.ComponentMaster.length = 0;
                angular.extend($scope.ComponentMaster, response.data);
            }
            else {
                $scope.ShowEmptyRow = true;
                $scope.ComponentMaster.length = 0;
            }
        }, function (error) {
            alert(error.data);
        });
    }

} ]);

AngularApp.service("ConfigurationService", function ($http) {

// Call comes here...
this.GetComponentMasterDetails = function () {
    // Call comes here... But this $http.get - not calling MVC controller Action method. 
    // I kept my breakpoint in MVC controller method, but not executed the method. 
    // So this Service just returning old records. This is the reason the View showing old records. 
    // If i press Ctrl + F5, it is calling MVC controller message & showing the updated records.
    return $http.get('/Configuration/GetComponentMasterDetails');
};

// Control comes here... Then calling MVC controller Action method.. Saving data into DB & returned execution message.
this.SaveComponentMaster = function (ComponentModel) {
    var response = $http({
        method: 'POST',
        url: '/Configuration/SaveComponentMaster/',
        data: { ComponentModel: ComponentModel }
    });
    return response;
};
});

Контроллер MVC

 [NoCache]
 [HttpGet]
    public ActionResult GetComponentMasterDetails()
    {
        RNDDBContext dbContext = new RNDDBContext();
        var result = dbContext.ExecuteStoreQuery<ComponentModel>("exec PROC_GET_COMPONENT_MASTER_DETAILS").ToList();
        return Json(result, JsonRequestBehavior.AllowGet);
    }

 [NoCache]
 [HttpPost]
    public JsonResult SaveComponentMaster(ComponentModel ComponentModel)
    {
        RNDDBContext dbContext = new RNDDBContext();
        var result = dbContext.ExecuteStoreQuery<string>("exec PROC_SAVE_COMPONENT_MASTER @ComponentID,@ComponentName,@Language,@IsActive,@ModifiedBy",
                                                           new SqlParameter("ComponentID", ComponentModel.ComponentID),
                                                            new SqlParameter("ComponentName", ComponentModel.ComponentName),
                                                            new SqlParameter("Language", ComponentModel.Language),
                                                            new SqlParameter("IsActive", ComponentModel.IsActive),
                                                            new SqlParameter("ModifiedBy", ComponentModel.ModifiedBy)
                                                        ).FirstOrDefault();
        return Json(result, JsonRequestBehavior.AllowGet);
    }

 public class NoCache : ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
        filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
        filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
        filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        filterContext.HttpContext.Response.Cache.SetNoStore();
        base.OnResultExecuting(filterContext);
        }
  }
Теги:
asp.net-mvc-4

1 ответ

1

Инициализируйте свой $ scope.ComponentMaster в верхней части контроллера

AngularApp.controller("ConfigurationController", ['$scope', 'ConfigurationService', function ($scope, ConfigurationService) {

        $scope.ComponentMaster = [];

        GetComponentMasterDetails();

и просто пуст, а затем повторно заселяем, как только вы вызываете GetComponentMasterDetails()

function GetComponentMasterDetails() {
    var ComponentMaster = ConfigurationService.GetComponentMasterDetails();
    ComponentMaster.then(function (response) {
        if (response.data != "") {
            $scope.ShowEmptyRow = false;
            // Empty the ComponentMaster array
            $scope.ComponentMaster.length = 0;
            // Add the retrieved data
            angular.extend($scope.ComponentMaster, response.data)
        }
        else {
            $scope.ShowEmptyRow = true;
            // Empty the ComponentMaster array
            $scope.ComponentMaster.length = 0;
        }
    }, function (error) {
        alert(error.data);
    });
}

Эта проблема аналогична этому

  • 0
    Спасибо за ваш ответ..! Я обновил код, как вы предложили. Но все же проблема не решена. Проблема не в записях $ scope.ComponentMaster, сама служба не возвращает обновленные записи. Я обновил свой блок кода выше.
  • 1
    Возможно, результаты из / Configuration / GetComponentMasterDetails кэшируются в вашем браузере. Попробуйте добавить другой параметр в ваш запрос GET и посмотрите, изменится ли результат
Показать ещё 2 комментария

Ещё вопросы

Сообщество Overcoder
Наверх
Меню