简体   繁体   English

使用Angularjs从Ajax调用在服务器代码处获得的值变为空

[英]Values getting null at server code from ajax call using Angularjs

I have built a MVC application to insert form data into DB. 我已经构建了一个MVC应用程序,可以将表单数据插入DB。 I used angularjs library with html5 & bootstrap. 我在html5和bootstrap中使用了angularjs库。

Below is the some major lines in HTML. 以下是HTML中的几行主要内容。 form tag: 表单标签:

 <form ng-app='MyData' ng-controller='DataController'>

Button (): 按钮():

<input type="button" value="Submit" ng-click="addUser();" id="btnSubmitAddUsr" class="btn btn-success" />

Below is the ajax call using Jquery & angular js: 下面是使用Jquery和angular js的ajax调用:

var myData = angular.module('MyData', []);
myData.controller("DataController", function ($scope, $http) {
     $scope.addUser = function () {
                $.ajax({
                    type: 'POST',
                    contentType: 'application/json; charset=utf-8',
                    data: JSON.stringify($scope.usrFName, $scope.usrEmail, $scope.usrPhone, $scope.selectApp.id, $scope.usrRole),
                    url: '/Home/AddUser',
                    success: function (data, status) {
                        $scope.clear();
                    },
                    error: function (status) { }
                });
            };
 });

C# method: C#方法:

[HttpPost]
public JsonResult AddUser(string usrFName, string usrEmail, string usrPhone, string usrApp, string usrRole)
    {
        var db = new SchedulerEntities();
        db.Users.Add(new User { Name = usrFName, Password = "testPwd", Email = usrEmail, Phone = usrPhone, ApplicationId = Convert.ToInt32(usrApp), RoleId = Convert.ToInt32(usrRole) });
        db.SaveChanges();
        return null;
    }

The above C# methods gets called; 上面的C#方法被调用; but the parameters shows null. 但参数显示为空。 Also when I check the $scope variables from browser; 同样,当我从浏览器检查$ scope变量时; the form values shows correct there. 表单值在那里显示正确。

Please suggest. 请提出建议。

You generally don't want to use $scope as your model and instead create an object for your model on the scope...you'll run into some other issues with prototype inheritance the way you are currently doing it. 通常,您不想使用$ scope作为模型,而是在范围内为模型创建一个对象...您会遇到与原型继承有关的其他一些问题,如您目前所做的那样。 When you use ng-model, you should always have a '.' 当您使用ng-model时,应该始终有一个'。'。 in the expression. 在表达式中。

You should also use $http instead of $.ajax (it'll handle the serialization for you and run a digest cycle when the call completes). 您还应该使用$ http而不是$ .ajax(它将为您处理序列化并在调用完成后运行摘要周期)。

var myData = angular.module('MyData', []);
myData.controller("DataController", function ($scope, $http) {
     $scope.form = {usrFName: '', usrEmail: '', usrApp: ''}; // initialize any other form variables 
     $scope.addUser = function () {
         $http.post('/Home/AddUser', $scope.form)
             .success(function(){$scope.clear();});
     };
 });

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

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