【问题标题】:How to call async Task<ActionResult> from angular controller如何从角度控制器调用异步任务<ActionResult>
【发布时间】:2018-01-04 06:21:35
【问题描述】:

这是我的角度控制器

        //Save AddNewEmployee functionality 
        EDC.SaveNewEmployee = function () {
            if (EDC.AddNewEmployeeFormValidator.validate()) {
                var UserID = '0',
                CandidateSubmit = '';
                if (EDC.isEdit) {
                    UserID = EDC.rowIdToEdit;
                }
                EmployeeDetailService.SaveNewEmployee(EDC.NewEmpAdd, UserID, CandidateSubmit).then(function (response) {
                    //Close popup window 
                    EDC.AddNewEmployeeWindow.data("kendoWindow").close();
                    //EDC.NewEmpSave = response;
                    EDC.EmployeeDetailsGrid.dataSource.read();

                });
            }
        };

这个是我的 MVC 控制器。

    public async Task<ActionResult> SavePermanentEmployee(Employee model)
    {
        //Sending mail to BU
        string DisplayName = "New Employee";
        //Sending mail to Employee
        string EmpDisplayName = "Price credentials";
        BAL_Employee objBalEmp = new BAL_Employee();
        Price_PMS_DAL.Employee emp = new Price_PMS_DAL.Employee();
        emp.ID = model.ID;
        emp.EmpID = model.employeeID ?? Convert.ToString(model.employeeID).ToUpper();
        emp.ReferredBy = model.referredby;
        emp.DOJ = model.dateOfJoining;
        emp.Status = 1;
        emp.Email = model.email;
        emp.BUID = model.businessUnitID;
        emp.ShiftID = model.ShiftID;
        emp.ModifiedBy = Session["EmpID"].ToString();
        var lstNewEmployeeCreated = BAL_Employee.GetEmployees();
        var result = lstNewEmployeeCreated.Where(s => s.employeeID == emp.EmpID).FirstOrDefault();

        if (result != null)
        {
            return Json("Employee ID already exists.", JsonRequestBehavior.AllowGet);
        }
        else
        {

            int empSave = objBalEmp.UpdateEmployee(emp);
            BAL_Login objBalLog = new BAL_Login();
            if (empSave == 1)
            {
                TempData["Datarefresh"] = "refresh";
                lstemp = null;
                string[] datastr = emp.Email.Split(new string[] { "@" }, StringSplitOptions.None);
                int empLoginSave = objBalLog.AddUser(new Price_PMS_DAL.Login { UserName = datastr[0].Trim(), EmpID = emp.EmpID, BUID = emp.BUID, ShiftID = emp.ShiftID });
                if (empLoginSave == 1)
                {
                    var data = BAL_Employee.FilterEmployeeByParam("Select TOP 1 * FROM Employee where Status=1 order by EmpID desc");
                    Price_PMS_DAL.Emp_Leave modelBal = new Price_PMS_DAL.Emp_Leave();
                    modelBal.EmpID = emp.EmpID;
                    int empLeavebalSave = objBalEmp.CreateEmployeeLLeaveBalRec(modelBal);
                    if (empLeavebalSave == 1)
                    {
                        Price_PMS_BAL.Models.BusinessUnit.BU Bus = BAL_BU.GetSPBUs().Where(b => b.ID == model.businessUnitID).First();
                        if (Bus != null)
                        {
                            //Sending Mail to BU when new Permanent employee added into the system
                            StringBuilder str = new StringBuilder();
                            StringBuilder cc = new StringBuilder();
                            StringBuilder to = new StringBuilder();
                            to.Append(@" " + Bus.BUHeadEmailId);
                            str.Append(@"Hello,<br><br>&nbsp;&nbsp;&nbsp;New Employee named <b>" + model.name + "</b> has been added to " + Bus.BUName + " BU " + " on " + DateTime.Now.ToShortDateString() + ".<br><br>&nbsp;&nbsp;&nbsp;Regards,<br>&nbsp;&nbsp;&nbsp;PRICE");
                            bool x = await Price_PMS_BAL.Models.Email.Email.SendEmail(cc, to, "New Employee Added", str.ToString(), DisplayName);
                            //End
                        }
                        //Sending Mail to Employee when new Permanent employee added into the system
                        if (emp != null)
                        {
                            StringBuilder str = new StringBuilder();
                            StringBuilder cc = new StringBuilder();
                            StringBuilder to = new StringBuilder();
                            to.Append(@" " + emp.Email);

                            //Username with last name Split
                            String[] Emailstring = emp.Email.Split(new[] { '@' });
                            String username = Emailstring[0];                   

                            //Username split with out last name

                            String[] Uname = username.Split(new[] { '.' });
                            String Unamestr = Uname[0];
                            Unamestr = Unamestr.Substring(0, 1).ToUpper() + Unamestr.Substring(1);
                            var PriceURL = "https://price.dreamorbit.com/";
                            str.Append(@"Hi " + Unamestr + ",<br><br>&nbsp;Welcome to DreamOrbit. Please login to PRICE (Projects, Resource Information & Cost Estimation) to apply for your leaves and to see your ratings etc. on a regular basis with following credentials:<br><br><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b><u>URL</u></b> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;:  <a href=" + PriceURL + " target=_blank>" + PriceURL + "</a>  <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b><u>Username</u></b> :  " + username + "<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b><u>Password</u></b> : [Your System Password]<br><br><br>&nbsp;We wish you a long and mutually beneficial association with DreamOrbit. For any queries please reach out to Panchali (panchali.bharali@dreamorbit.com).<br><br>&nbsp;Regards,<br>&nbsp;PRICE");
                            bool x = await Price_PMS_BAL.Models.Email.Email.SendEmail(cc, to, "PRICE Credentials", str.ToString(), EmpDisplayName);
                        }
                        //End

                        return Json("Saved Successfully", JsonRequestBehavior.AllowGet);
                    }
                    else { return Json("Error occurred while saving data ", JsonRequestBehavior.AllowGet); }
                }
                else
                    return Json("Error occurred while saving data ", JsonRequestBehavior.AllowGet);

            }
            else
            {
                return Json("Error occurred while saving data ", JsonRequestBehavior.AllowGet);
            }
        }

    }

【问题讨论】:

    标签: angularjs model-view-controller


    【解决方案1】:

    通常 javascript 代码同步执行(默认),并且 javascript 有核心 promise 对象,用于使函数异步。

    Angularjs 有核心服务 $q 用于使函数异步。

    Angularjs 简单示例:

    angular.module("starter", [])
    .controller("myCtrl", function($scope, $q, $http){
    
        var GetData = function(){
            var root = 'https://jsonplaceholder.typicode.com';
            var defer = $q.defer();
            
            $http({
                method: "GET", 
                url: root + '/posts/1'
            }).then(function(response){
                //success call back
                defer.resolve(response);
            }, function(error){
                //error callbcall
                defer.reject();
            });
            return defer.promise;
        }; 
    
        $scope.AsynchCall = function(){
        GetData().then(function(response){
            //success call back        
            console.log(response);
            alert(JSON.stringify(response));  
        }, function(error){
            //error callbcall
            console.log(JSON.stringfy(error));
            alert(error);  
        });
        }; 
    }); 
    <html>
    <head> 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    </head> 
    
    <body ng-app="starter" ng-controller="myCtrl"> 
    <button ng-click="AsynchCall()"> Asynch call </button> 
    </body> 
    
    </html> 

    【讨论】:

      【解决方案2】:

      这是因为 JSON.stringify 会返回 toJSON 函数的返回值,如果存在的话。

      【讨论】:

        猜你喜欢
        • 2021-10-01
        • 1970-01-01
        • 2014-05-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-04
        • 1970-01-01
        相关资源
        最近更新 更多