使用Angular JS

时间:2016-05-16 15:49:22

标签: angularjs asp.net-mvc

我有一个包含文本框,下拉列表和复选框的表单。我面临的挑战是将几个复选框项提交到数据库中。数据确实已提交,但它只提交表单上的最后一个检查项目。

这是我的用户界面

<div class="block type-3">
    <div class="container">
        <div class="row post animated fadeInUp">
            <div class="col-xs-12 form-block">
                <div ng-controller="tutorequestController">
                    <form name="tutrequestform" novalidate>
                        <div class="form-text">Required fields are <span class="text-blue">*</span>. Fill out the form and we'll contact you soon</div>
                        <div class="row">
                            <div class="col-xs-12 col-sm-6">
                                <input ng-model="tutorRequest.firstname" name="firstname" type="text" class="form-input" placeholder="Firstname *" required />
                            </div>
                            <div class="col-xs-12 col-sm-6">
                                <input ng-model="tutorRequest.lastname" name="lastname" type="text" class="form-input" placeholder="Lastname *" required />
                            </div>
                            <div class="col-xs-12 col-sm-6">
                                <input ng-model="tutorRequest.phonenumber" name="phonenumber" type="number" class="form-input" placeholder="Phone Number *" required />
                            </div>
                            <div class="col-xs-12 col-sm-6">
                                <input ng-model="tutorRequest.phonenumber2" name="phonenumber2" type="number" class="form-input" placeholder="Re-type Phone Number *" required />
                            </div>
                            <div class="col-xs-12 col-sm-6">
                                <input ng-model="tutorRequest.emailaddress" name="emailaddress" type="email" class="form-input" placeholder="Email Address *" required />
                            </div>
                            <div>
                                <div ng-controller="stateLGAController">
                                    <div class="col-xs-12 col-sm-6">
                                        <!--<select ng-change="GetStateLgas()" ng-options="moreState as moreState.state1 for moreState in moreStates track by moreState.state_id" ng-model="select" class="form-input"><option>Select Your State</option></select>-->
                                        <select ng-model="tutorRequest.state_id" ng-change="GetStateLgasByid(tutorRequest.state_id)"
                                                ng-options="moreState.state_id as moreState.state1 for moreState in moreStates" class="form-input">
                                            <option>Select Your State</option>
                                        </select><!---->
                                    </div>
                                    <div class="col-xs-12 col-sm-6">
                                        <select ng-model="tutorRequest.lga_id"
                                                ng-options="lga.lga_id as lga.local_govt for lga in stateLGA" class="form-input">
                                            <option>Select Your L.G.A</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            <div class="col-xs-12">
                                <textarea ng-model="tutorRequest.address" class="form-input" name="address" placeholder="House Address *" required></textarea>
                            </div>
                            <div class="col-xs-12 col-sm-6">
                                <select ng-model="tutorRequest.numofchild" name="numofchild" class="form-input">
                                    <option value='Select-Number-of-Child-for-Tutor'>Select number of Child/ren for Tutor</option>
                                    <option value='1'>1</option>
                                    <option value='2'>2</option>
                                    <option value='3'>3</option>
                                    <option value='4'>4</option>
                                    <option value='5'>5</option>
                                </select>
                            </div>
                            <div class="col-xs-12 col-sm-6">
                                <input ng-model="tutorRequest.classrangeandage" class="form-input" name="classrangeandage" type="text" required placeholder="Class range of each child and age respectively *" />
                            </div>
                            <div class="col-xs-12 form-text">
                                <span  class="text-blue">What subject would the tutor teach? Tick appropriate subject below.</span>
                            </div>
                            <div ng-app="app" ng-controller="subjectController">
                                <div ng-repeat="sub in tutorRequest.tutorsubject" class="col-xs-12 col-sm-4">
                                    <div class="chBoxPad">
                                        <input ng-model="tutorRequest.tutorsubject[$index].checked" type="checkbox" id="{{sub.sub_id}}" name="{{sub.subject1+'_'+$index}}" ng-change="updateChecked()" />
                                        <label for="{{sub.sub_id}}"><span></span>{{sub.subject1}}</label>
                                    </div>
                                </div>
                            </div>

                            <div class="col-xs-12">
                                <select ng-model="tutorRequest.preferredsexoftutor" name="sex" id="sex" class="form-input">
                                    <option value="preferredsexoftutor" selected="selected">Preferred Sex of Tutor</option>
                                    <option value="any">Any</option>
                                    <option value="Male">Male</option>
                                    <option value="Female">Female</option>
                                </select>
                            </div>
                            <div class="col-xs-12 col-sm-6">
                                <input ng-model="tutorRequest.childcurrentschool" name="childcurrentschool" type="text" class="form-input" placeholder="Current School of Child *" required />
                            </div>
                            <div class="col-xs-12">
                                <select ng-model="tutorRequest.schoolcurriculum" name="schoolcurriculum" id="curi" class="form-input">
                                    <option value="">What curriculum does the school use</option>
                                    <option value="Not Sure">Not Sure</option>
                                    <option value="British Curriculum">British Curriculum</option>
                                    <option value="American Curriculum">American Curriculm</option>
                                    <option value="Nigerian Curriculum">Nigerian Curriculum</option>
                                    <option value="Combination of British and Nigerian">Combination of British and Nigerian</option>
                                    <option value="Question doesnt apply to me">Question doesn't apply to me</option>
                                </select>
                            </div>
                            <div class="col-xs-12 col-sm-6">
                                <select ng-model="tutorRequest.urgencyoftutor" name="urgencyoftutor" id="urgencyoftutor" class="form-input">
                                    <option value="">Urgency of tutor</option>
                                    <option value="Urgently" selected="selected">Urgently</option>
                                    <option value="In 1 Week">In a Week</option>
                                    <option value="In 2 Weeks">In 2 Weeks</option>
                                    <option value="In a Month">In a Month</option>
                                </select>
                            </div>
                            <div class="col-xs-12 col-sm-6">
                                <select ng-model="tutorRequest.calltime" name="calltime" id="calltime" class="form-input">
                                    <option value="" selected="selected">What time of the day would you like to be called</option>
                                    <option value="Anytime">Anytime</option>
                                    <option value="8 to 12">Morning - between 8am and 12noon</option>
                                    <option value="12 to 3">Afternoon - between 12noon to 3pm</option>
                                    <option value=" 3 to 6">Evening - between 3pm to 6pm</option>
                                </select>
                            </div>
                            <div class="col-xs-12 col-sm-6">
                                <select ng-model="tutorRequest.frequencyoftutor" name="frequencyoftutor" id="frequencyoftutor" class="form-input">
                                    <option value="">How many times a week would you like the tutor to come</option>
                                    <option value="1">Once a week</option>
                                    <option value="2">2 times a week</option>
                                    <option value="3">3 times a week</option>
                                    <option value="4">4 times a week</option>
                                    <option value="5">5 times a week</option>
                                    <option value="6">6 times a week</option>
                                    <option value="7">7 times a week</option>
                                </select>
                            </div>
                            <div class="col-xs-12 col-sm-6">
                                <select ng-model="tutorRequest.tutorhrs" name="tutorhrs" id="tutorhrs" class="form-input">
                                    <option value="">How many hours per day should tutoring hold</option>
                                    <option value="1" selected="selected">1 hr</option>
                                    <option value="2">2 hrs</option>
                                    <option value="3">3 hrs</option>
                                    <option value="4">4 hrs</option>
                                    <option value="5">5 hrs</option>
                                    <option value="6">6 hrs</option>
                                    <option value="7">7 hrs</option>
                                </select>
                            </div>
                            <div class="col-xs-12 col-sm-6">
                                <input ng-model="tutorRequest.goal" name="goal" type="text" class="form-input" placeholder="Specific goal for tutoring session" required />
                            </div>
                            <div class="col-xs-12 col-sm-6">
                                <select ng-model="tutorRequest.howdidyouhearaboutus" name="howdidyouhearaboutus" class="form-input">
                                    <option value="">How did you hear about us</option>
                                    <option value="Google" selected="selected">Google</option>
                                    <option value="Facebook">Facebook</option>
                                    <option value="I got an SMS from Prepschool">I got an SMS from Prepschool</option>
                                    <option value="Twitter">Twitter</option>
                                    <option value="Nairaland">Nairaland</option>
                                    <option value="I saw a flyer">I saw a flyer</option>
                                    <option value="Prepschool Brochure">Prepschool Brochure</option>
                                    <option value="A friend / member of household">A friend / member of household</option>
                                    <option value="Other">Other</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-xs-12">
                            <span class="button">
                                <button type="submit" class="submit" ng-click="CreateTutRequest(tutorRequest, tutrequestform.$valid)">Submit Request</button>
                            </span>
                            <!--<td><input type="submit" ng-click="CreateEmployee(Emp, myForm.$valid)" value="Create" /></td>
                <td><input type="submit" ng-click="UpdateEmployee(Emp)" value="Update" /></td>-->
                            <span class="success"></span>
                        </div>

                    </form>
                </div>
            </div>
        </div>

    </div>
</div>

以下是图像格式的UI的部分图形表示。 enter image description here 这是我的angularJs控制器页面。

myApp.factory('crudServiceTutorrequest', function ($http) {
    // Create an object and start adding methods to the object.
    crudTutRObj = {};

    // Add create method to the crudTutRObj
    crudTutRObj.getAll = function () {
        var tutorRequests;

        tutorRequests = $http({ method: 'GET', url: '/Tutorrequest/Index' }).
        then(function (response) {
            return response.data;
        });
        return tutorRequests;
    }

    crudTutRObj.getStates = function () {
        var ddlStates;

        ddlStates = $http({ method: 'GET', url: '/States/Index' }).
        then(function (response) {
            return response.data;
        });
        return ddlStates;
    }

    crudTutRObj.getSubject = function () {
        var Subjects;

        Subjects = $http({ method: 'GET', url: '/Subject/Index' }).
        then(function (response) {
            return response.data;
        });
        return Subjects;
    }

    crudTutRObj.createTutRequest = function (tutRequest) {
        var tutorRequest;

        tutorRequest = $http({ method: 'POST', url: '/Tutorrequest/Create', data: tutRequest }).
            then(function (response) {
                return response.data;
            });
        return tutorRequest;
    }

    crudTutRObj.getById = function (id) { }

    crudTutRObj.update = function (fms) { }

    crudTutRObj.deleteById = function (id) { }

    return crudTutRObj;
});

myApp.controller('tutorequestController', function ($scope, crudServiceTutorrequest) {

    // Get all tutorRequests
    //crudServiceTutorrequest.getAll().then(function (result) {
    //    $scope.tutorRequests = result;
    //})

    // Get data for states to populate the states dropdownlist
    crudServiceTutorrequest.getStates().then(function (result) {
        $scope.moreStates = result;
    })   

    // Submit the form with the create function
    $scope.CreateTutRequest = function (tutorRequest) {
        crudServiceTutorrequest.createTutRequest(tutorRequest).then(function (result) {
            $scope.Msg = "Tutor Request has been submitted successfully!";
        });
    }
});

myApp.controller('stateLGAController', function ($scope, $http) {

    $scope.GetStateLgas = function () {
        $http({ method: 'Get', url: '/StateLGA/Index' })
        .then(function (response) {
            $scope.stateLGA = response.data;
        });
    };

    $scope.GetStateLgasByid = function (state_id) {
        $http({ method: 'Get', url: '/StateLGA/GetlgaByStateid/' + state_id })
        .then(function (response) {
            $scope.stateLGA = response.data;
        });
    };
});

angular.module("app", []).controller('subjectController', ['$scope', function ($scope, crudServiceTutorrequest) {
    var subjects;
    subjects = crudServiceTutorrequest.getSubject().then(function (result) {
        $scope.subjects = result;
    })

    $scope.tutorRequest = {
        tutorsubject: subjects
    };

    angular.forEach($scope.subjects, function (subject) {
        var sub = angular.merge({ checked: false }, subject);
        $scope.tutorRequest.tutorsubject.push(sub);
    });

    $scope.allSubjectChecked = [];
    $scope.updateChecked = function () {
        console.log($scope.tutorRequest.tutorsubject);
        $scope.allSubjectChecked = [];
        angular.forEach($scope.tutorRequest.tutorsubject, function (sub) {
            if (sub.checked) {

                $scope.allSubjectChecked.push(sub);
            }
        });
    }
}]);

最后,js文件将所有页面路由到ng-view

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

myApp.config(function ($routeProvider) {
    $routeProvider.when('/Department', {
        templateUrl: 'Templates/Admin/Department/Department.html',
        controller: 'departmentController'
    });
    $routeProvider.when('/Employee', {
        templateUrl: 'Templates/Admin/Employee/Employee.html',
        controller: 'employeeController'
    });
    $routeProvider.when('/Aboutus', {
        templateUrl: 'Templates/User/Aboutus/Aboutus.html',
        controller: ''
    });
    $routeProvider.when('/Contactus', {
        templateUrl: 'Templates/User/Contactus/Contactus.html',
        controller: ''
    });
    $routeProvider.when('/Tutorregistration', {
        templateUrl: 'Templates/User/Tutorregistration/Tutorregistration.html',
        controller: ''
    });
    $routeProvider.when('/Tutorrequest', {
        templateUrl: 'Templates/User/Tutorrequest/Tutorrequest.html',
        controller: 'tutorequestController'
    });
    $routeProvider.otherwise({
        redirectTo: '/Home',
        templateUrl:'Templates/User/Home/Home.html'
    });
});

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

问题可能是MVC没有绑定复选框值,如果它是false。试试这个:

<div ng-controller="subjectController">
    <div ng-repeat="sub in subjects" class="col-xs-12 col-sm-4">
        <div class="chBoxPad">
            <input ng-model="tutorRequest.tutorsubject" type="checkbox" id="{{sub.sub_id}}" name="{{sub.subject1}}" ng-true-value="{{sub.sub_id}}" />
            <input type="hidden" value="false" name="{{sub.subject1}}" />
            <label for="{{sub.sub_id}}"><span></span>{{sub.subject1}}</label>
        </div>
    </div>
</div>

如果复选框为false,则会提交隐藏字段。相反,当它成立时,将同时提交两个字段(false和true),MVC将其作为“真实”值。

我知道这听起来很奇怪,但它是MVC如何运作的。如果您使用@ Html.CheckBoxFor(),您可以自己看到。你将拥有相同的输出。

答案 1 :(得分:0)

问题在于你为每个科目设置了相同的ng模型。 Angular不为复选框列表构建数组,您必须将每个复选框绑定到单独的模型。

这样做的最好方法是使用所有可能的值初始化tutorsubject,并将字段'checked'设置为false,如下所示:

angular.module("app", []).controller("ctrl", ['$scope', function($scope){
  $scope.tutorRequest = {tutorsubject : [{sub_id:1, subject1:"Foo"},
                                     {sub_id:2, subject1:"Foo2"}]};
    angular.forEach($scope.subjects,function(subject){          
          var sub = angular.merge({checked:false}, subject);
          $scope.tutorRequest.tutorsubject.push(sub);
    });
  
  $scope.allSubjectChecked = [];
  $scope.updateChecked = function(){
    console.log($scope.tutorRequest.tutorsubject);
    $scope.allSubjectChecked = [];
    angular.forEach($scope.tutorRequest.tutorsubject, function(sub){
        if(sub.checked){

            $scope.allSubjectChecked.push(sub);
        }
    });
  }
  }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>  

 <div ng-app="app" ng-controller="ctrl">
    <div ng-repeat="sub in tutorRequest.tutorsubject" class="col-xs-12 col-sm-4">
        <div class="chBoxPad" >
            <input ng-model="tutorRequest.tutorsubject[$index].checked" type="checkbox" id="{{sub.sub_id}}" name="{{sub.subject1+'_'+$index}}" ng-change="updateChecked()"/>
             <label for="{{sub.sub_id}}"><span></span>{{sub.subject1}}</label>
         </div>
    </div>
    <h2> Subject selected : </h2>
    <div ng-repeat="selected in allSubjectChecked">
      <span ng-bind="selected.subject1"></span><br/>
    </div>
 </div>

当然,如果这种存储数据的方式与你的后端不匹配;您可以在提交表单时过滤它们。为了在执行此操作时不更改显示的模型,请在var myData = angular.merge({},$scope.tutorRequest);

的结果中执行此操作

编辑:通过工作代码段更改示例代码