简体   繁体   English

后续操作后AngularJS控制器未调用MVC控制器

[英]AngularJS controller not calling MVC controller after post action

I'm an Angularjs beginner and stuck somewhere in the code. 我是Angularjs的初学者,被卡在代码中的某个地方。 I'm working on a CRUD operation sample and when I update the values on the view it gets updated successfully in the database but updated values are not coming immediately unless the page is reloaded. 我正在研究一个CRUD操作示例,当我更新视图上的值时,它将成功在数据库中更新,但是除非重新加载页面,否则更新后的值不会立即出现。

Below is the code: 下面是代码:

View- 视图-

    <h2>Customer Details</h2>
<div ng-app="myApp">
    <div ng-controller="myCtrl" ng-init="GetAllData()" class="divList">
        <p class="divHead">List of Customers</p>
        <table cellpadding="12" class="table table-bordered table-hover">
            <tr>
                <td>
                    <b>ID</b>
                </td>
                <td>
                    <b>Name</b>
                </td>
                <td>
                    <b>City</b>
                </td>
                <td>
                    <b>Contact</b>
                </td>
                <td>
                    <b>EmailID</b>
                </td>
                <td>
                    <b>Actions</b>
                </td>
            </tr>
            <tr ng-repeat="Emp in employees">
                <td>
                    {{Emp.CustomerID}}
                </td>
                <td>
                    {{Emp.Name}}
                </td>
                <td>
                    {{Emp.Address}}
                </td>
                <td>
                    {{Emp.Mobileno}}
                </td>
                <td>
                    {{Emp.EmailID}}
                </td>
                @*<td>
                    {{Emp.Mobileno}}
                </td>*@
                <td>
                    <input type="button" class="btn btn-warning" value="Update" ng-click="UpdateEmp(Emp)" />
                    <input type="button" class="btn btn-danger" value="Delete" ng-click="DeleteEmp(Emp)" />
                </td>
            </tr>
        </table>
        <div class="form-horizontal" role="form">
            <div class="container">
                <div class="row">
                    <h2>
                        <span id="spn">Add New Customer</span>
                    </h2>
                </div>
                <div class="row">
                    <div class="col-sm-6 col-lg-4">
                        <div class="form-group">
                            <label class="col-md-4 control-label">Name:</label>
                            <div class="col-md-8">
                                <input type="text" class="form-control" id="inputEmail" placeholder="Name" ng-model="EmpName" required>
                            </div>
                        </div>
                    </div>
                    <div class="col-sm-6 col-lg-4">
                        <div class="form-group">
                            <label class="col-md-4 control-label">City:</label>
                            <div class="col-md-8">
                                <input type="text" class="form-control" id="inputPassword" placeholder="City" ng-model="EmpCity">
                            </div>
                        </div>
                    </div>
                    <div class="col-sm-6 col-lg-4">
                        <div class="form-group">
                            <label class="col-md-4 control-label">Contact:</label>
                            <div class="col-md-8">
                                <input type="text" class="form-control" id="inputLabel3" placeholder="Contact" ng-model="Contact">
                            </div>
                        </div>
                    </div>
                    <div class="col-sm-6 col-lg-4">
                        <div class="form-group">
                            <label class="col-md-4 control-label">Email ID:</label>
                            <div class="col-md-8">
                                <input type="text" class="form-control" id="inputLabel3" placeholder="Email ID" ng-model="Email">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-6 col-lg-4">
                        <input type="button" id="btnSave" class="form-control btn-space" value="Submit" ng-click="InsertData()" />
                    </div>
                </div>
            </div>
        </div>
    </div>
    @Html.Hidden("CustomerID")
</div>

MVC Controller- MVC控制器-

        public ActionResult Index()
        {
            return View();
        }
        public JsonResult Get_AllEmployee()
        {
            using(TestDBEntities obj=new TestDBEntities())
            {
            List<Employee> emp=obj.Employees.ToList();
            return Json(emp, JsonRequestBehavior.AllowGet);
            }
        }
        public string Update_Employee(Employee Emp)
        {
            if (Emp != null)
            {
                using (TestDBEntities Obj = new TestDBEntities())
                {
                    var Emp_ = Obj.Entry(Emp);
                    Employee EmpObj = Obj.Employees.Where(x => x.CustomerID == Emp.CustomerID).FirstOrDefault();
                    EmpObj.Address = Emp.Address;
                    EmpObj.Name = Emp.Name;
                    EmpObj.Mobileno = Emp.Mobileno;
                    EmpObj.EmailID = EmpObj.EmailID;
                    Obj.SaveChanges();
                    return "Employee Updated Successfully";
                }
            }
            else
            {
                return "Employee Not Updated! Try Again";
            }
        } 

Angular Code- 角度代码

var app = angular.module("myApp", []);
app.controller("myCtrl", function ($scope, $http) {
    //debugger;
    $scope.InsertData = function () {
        var Action = document.getElementById("btnSave").getAttribute("value");
        if (Action == "Submit") {
            $scope.Employe = {};
            $scope.Employe.Name = $scope.EmpName;
            $scope.Employe.Address = $scope.EmpCity;
            $scope.Employe.Mobileno = $scope.Contact;
            $scope.Employe.EmailID = $scope.Email;
            $http({
                method: "post",
                url: "http://localhost:12345/Employee/Insert_Employee",
                datatype: "json",
                data: JSON.stringify($scope.Employe)
            }).then(function (response) {
                alert(response.data);
                $scope.GetAllData();
                $scope.EmpName = "";
                $scope.EmpCity = "";
                $scope.Contact = "";
                $scope.Email = "";
            })
        } else {
            debugger;
            $scope.Employee = {};
            $scope.Employee.Name = $scope.EmpName;
            $scope.Employee.Address = $scope.EmpCity;
            $scope.Employee.Mobileno = $scope.Contact;
            $scope.Employee.EmailID = $scope.Email;
            $scope.Employee.CustomerID = document.getElementById("CustomerID").value;
            $http({
                method: "post",
                url: "http://localhost:12345/Employee/Update_Employee",
                datatype: "json",
                data: JSON.stringify($scope.Employee)
            }).then(function (response) {
                debugger;
                alert(response.data);
                //$scope.employees.length = 0;
                $scope.GetAllData();
                //$scope.$apply();
                $scope.EmpName = "";
                $scope.EmpCity = "";
                $scope.Contact = "";
                $scope.Email = "";
                document.getElementById("btnSave").setAttribute("value", "Submit");
                document.getElementById("btnSave").style.backgroundColor = "cornflowerblue";
                document.getElementById("spn").innerHTML = "Add New Customer";
            })
        }
    }
    $scope.GetAllData = function () {
        debugger;
        $http({
            method: "get",
            url: "http://localhost:12345/Employee/Get_AllEmployee"
        }).then(function (response) {
            $scope.employees = response.data;
            //angular.extend($scope.employees, response.data);
            //$scope.$apply();
        }, function () {
            alert("Error Occured!");
        })
    };

    $scope.UpdateEmp = function (Emp) {
        debugger;
        document.getElementById("CustomerID").value = Emp.CustomerID;
        //document.getElementById("Birthdate").value = Emp.Birthdate;
        $scope.EmpName = Emp.Name;
        $scope.EmpCity = Emp.Address;
        $scope.Contact = Emp.Mobileno;
        $scope.Email = Emp.EmailID;
        document.getElementById("btnSave").setAttribute("value", "Update");
        document.getElementById("btnSave").style.backgroundColor = "Yellow";
        document.getElementById("spn").innerHTML = "Update Employee Information";
    }

If you want update your data in table when your update is succesfuly you need to get your object from your table in then method and uptdate your object. 如果要在更新成功后更新表中的数据,则需要在then方法中从表中获取对象并更新对象。

Exemple: 例:

JS JS

app.controller('myCtrl', myCtrl)
myCtrl.$inject = ['$scope','$http'];
function myCtrl($scope, $http){
    var vm = this;
    vm.employee = {
         id:'',
         name:'',
         age:''
    }
    vm.employees = [];
    vm.update = update;
    vm.preupdate = preupdate;

    function init(){
        for(var i = 0; i < 10; i ++){
            vm.employees.push({id:i, name:'employee '+i, age: i});
        }
    }
    init();


    function preupdate(emp){
        vm.employee.id = emp.id;
        vm.employee.name = emp.name;
        vm.employee.age = emp.age;
    }

    function update(){


         $http({
             method:'POST',
             data: JSON.stringify(vm.employee),
             url: 'urlFromControllerMVC',
             headers:{
               'Content-Type': 'application/json'
             }
         }).then(success);

        function success(response){
            var obj = vm.employees.filter(x => x.id == emp.id);  //Get your object from your array
            obj.name = vm.employee.name;
            obj.age = vm.employee.age;
            vm.employee = {
                   id:'',
                   name:'',
                   age:''
            }
//after this your view is update
        }
    }

    //If you use function add just push your return object from controller MVC in your array of employees. 
}

HTML HTML

<div ng-controller="myCtrl as vm">

    <form novalidate ng-submit="vm.update()">  //or ng-click in your button
        //form for update your data
   </form>        

    <table>
        <tr>
            <td>id</td>
            <td>name</td>
            <td>age</td>
            <td></td>
        <tr>
        <tr ng-repeat="emp in vm.employees">
            <td>{{emp.id}}</td>
            <td>{{emp.name}}</td>
            <td>{{emp.age}}</td>
            <td><button ng-click="vm.preupdate(emp)">Update</button></td>  //
        </tr>
    </table>
</div>

I solved the issue by just changing the method from Get to Post in the angular code- 我通过将角度代码中的方法从Get更改为Post来解决了这个问题-

$scope.GetAllData = function () {
        debugger;
        $http({
            method: "post",
            url: "http://localhost:12345/Employee/Get_AllEmployee"
        }).then(function (response) {
            $scope.employees = response.data;
            //angular.extend($scope.employees, response.data);
            //$scope.$apply();
        }, function () {
            alert("Error Occured!");
        })
    };

when the crud operation is done..should re initialize the object.. 当完成crud操作时。应重新初始化对象。

[HttpPost]
        public JsonResult addProduct(ProductModels input)
        {

            Db.Products.Add(input);
            Db.SaveChanges();
            var products = Db.Products.ToList();
            return Json(products, JsonRequestBehavior.AllowGet);
        }

then get the product data inside controller function like this.. 然后像这样在控制器功能中获取产品数据。

$scope.addProduct = function(input)
    {
        console.log(input);     
        $.ajax({
            type: "POST",
            url: "/Angular/addProduct",
            dataType: "json",
            processData: false,
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({
                ProductCode: input.ProductCode,
                Productname: input.Productname,
                Price: input.Price
            }),
            success: function (resp) {
                console.log(resp);
                $scope.$apply(function () {
                    $scope.products = resp;
                    $scope.product = null;
                });
            }
        });
    }

i hope it works.. asp.net-mvc-and-angularjs-1.5 我希望它能工作.. asp.net-mvc-and-angularjs-1.5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM