AngularJS Service在CRUD操作后不调用控制器来获取更新的数据

时间:2016-07-28 12:40:32

标签: angularjs asp.net-mvc-4

我是AngularJS的初学者并尝试创建一个主数据输入屏幕,其中上部包含表单字段&下部包含表(GridView)以显示所有主条目。网格显示我最初运行应用程序时的所有数据。如果我添加/编辑任何新/旧记录,更新的数据不会反映在gridview中。 (即)如果我添加任何新条目,它将通过服务保存到数据库中,但不会反映在GridView中。即使我在菜单中导航也没有在网格中显示更新的数据。但是如果按Ctrl + F5,它会在网格中显示更新的数据。 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>

Angular Script:

 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);
        }
  }

1 个答案:

答案 0 :(得分:1)

在控制器顶部初始化$ scope.ComponentMaster

template <>
double convert<Mille,Km>(double val);
template <>
double convert<Milliseconds,Hours>(double val);

然后将其清空,然后在调用GetComponentMasterDetails()

后重新填充
AngularApp.controller("ConfigurationController", ['$scope', 'ConfigurationService', function ($scope, ConfigurationService) {

        $scope.ComponentMaster = [];

        GetComponentMasterDetails();

此问题与this

类似