【问题标题】:Populate drop down with MVC EF using AngularJS使用 AngularJS 使用 MVC EF 填充下拉列表
【发布时间】:2017-07-11 10:56:03
【问题描述】:

我最近开始使用 AngularJS。我的 HTML 中有一个下拉列表,我想使用数据库进行填充。但是我在控制器中找不到关于如何填充它的适当解决方案。下面是我的 C# 代码:-

 public JsonResult GetLocList()
    {
      IEnumerable<LocationTbl> ie = (from d in db.LocationTbls
                                      select d).ToList();
      //var ret = db.LocationTbls.Select(x => new { x.Id, x.LocName }).ToList();
      return Json(ie,JsonRequestBehavior.AllowGet);
    }

我的 HTML 是:-

 <tr>
    <td>
      Location :
    </td>
    <td>
      <select ng-model="CustLoc" ng-options="l.locname for l in location">
      <option value="">-- Select Country --</option>
      </select>
      <span class="error" ng-show="(f1.uCustLoc.$dirty || f1.$submitted) && f1.uCustLoc.$error.required">Location required!</span>
    </td>
  </tr>

我有一个用于 Angular 的 CustForm.js 文件,我想在其中将 Drop Down 填充为:-

angular.module('custFormApp', [])
        .controller('custDetailController', function ($scope, FileUploadService) {
            debugger;
            //Variables
            $scope.Message = "";
            $scope.FileInvalidMessage = "";
            $scope.SelectedFileForUpload = null;
            $scope.CustName = "";
            $scope.CustDoB = "";
            $scope.CustPhone = "";
            $scope.CustEMail = "";
            $scope.CustDescription = "";
            $scope.CustGender = "";

            $scope.IsFormSubmitted = false;
            $scope.IsFileValid = false;
            $scope.IsFormValid = false;

            //Form Validation
            $scope.$watch("f1.$valid", function (isValid) {
                $scope.IsFormValid = isValid;
                //GetLocList();
            });

            //File Validation
            $scope.ChechFileValid = function (file) {
                var isValid = false;
                if ($scope.SelectedFileForUpload != null) {
                    if ((file.type == 'image/png' || file.type == 'image/jpeg' || file.type == 'image/gif' || file.type == 'image/jpg') && file.size <= (512 * 1024)) {
                        $scope.FileInvalidMessage = "";
                        isValid = true;
                    }
                    else {
                        $scope.FileInvalidMessage = "Selected file is Invalid. (only file type png,jpg, jpeg and gif and 512 kb size allowed)";
                    }
                }
                else {
                    $scope.FileInvalidMessage = "Image required!";
                }
                $scope.IsFileValid = isValid;
            };

            //File Select event 
            $scope.selectFileforUpload = function (file) {
                $scope.SelectedFileForUpload = file[0];
            }

            //Save File
            $scope.SaveFile = function () {
                $scope.IsFormSubmitted = true;
                $scope.Message = "";
                $scope.ChechFileValid($scope.SelectedFileForUpload);
                if ($scope.IsFormValid && $scope.IsFileValid) {
                    FileUploadService.UploadFile($scope.CustName, $scope.CustDoB, $scope.CustPhone, $scope.CustEMail, $scope.CustDescription, $scope.CustGender, $scope.SelectedFileForUpload).then(function (d) {
                        alert(d.Message);
                        ClearForm();
                    }, function (e) {
                        alert(e);
                    });
                }
                else {
                    $scope.Message = "Please Fill Required Details";
                }
            };

            //Clear form 
            function ClearForm() {
                $scope.CustName = "";
                $scope.CustDoB = "";
                $scope.CustPhone = "";
                $scope.CustEMail = "";
                $scope.CustDescription = "";
                $scope.CustGender = "";
                //as 2 way binding not support for File input Type so we have to clear in this way
                //you can select based on your requirement
                angular.forEach(angular.element("input[type='file']"), function (inputElem) {
                    angular.element(inputElem).val(null);
                });

                $scope.f1.$setPristine();
                $scope.IsFormSubmitted = false;
            }
            
            function GetLocList() {
                $http({
                    method: 'Get',
                    url: '/Home/GetLocList'
                }).success(function (data, status, headers, config) {
                    $scope.location = data;
                    alert(data);
                }).error(function (data, status, headers, config) {
                    $scope.message = 'Unexpected Error';
                });
            }();

            //function getList() {
            //    debugger;
            //    var arrLocation = new Array();
            //    $http.get("/Home/LocList/").success(function (data) {

            //        $.map(data, function (item) {
            //            arrLocation.push(item.Id);
            //            arrLocation.push(item.LocName);
            //        });

            //        $scope.list = arrLocation;
            //    }).error(function (status) {
            //        alert(status);
            //    });
            //}

            //function getList($scope, $http) {
            //    $http.get("WebService/LocationService.asmx/GetLocation")
            //    .then(function (response) {
            //        $scope.list = response.data;
            //    })
            //}

        })

    //custDetailController Ends 
.factory('FileUploadService', function ($http, $q) { // explained abour controller and service in part 2
    var fac = {};
    fac.UploadFile = function (Name, DoB, Phone, EMail, Description, Gender, Photo) {
        var formData = new FormData();

        //We can send more data to server using append         
        formData.append("Name", Name);
        formData.append("DoB", DoB);
        formData.append("Phone", Phone);
        formData.append("EMail", EMail);
        formData.append("Description", Description);
        formData.append("Gender", Gender);
        formData.append("Photo", Photo);

        var defer = $q.defer();
        $http.post("/Home/SaveFiles", formData,
            {
                withCredentials: true,
                headers: { 'Content-Type': undefined },
                transformRequest: angular.identity
            })
        .success(function (d) {
            defer.resolve(d);
        })
        .error(function (f) {
            defer.reject(f);
        });

        return defer.promise;

    }
    return fac;

});

但是当我构建和运行代码时,下拉列表中没有值。如何填充下拉菜单?

【问题讨论】:

  • 您能否在您的success(实际上应该是then)中登录console.log(data),看看您是否从BE 那里获得任何数据?还有GetLocList() 是从哪里调用的?
  • 我想在页面加载时自动调用它。
  • 那么它是从哪里调用的呢?您的代码不会显示调用发生的位置,如果是这种情况,您的函数从未使用过,因此不会返回任何数据。
  • 我明白你的意思。我是角度的新手。请建议我如何在页面加载时自动调用它?
  • 假设您的控制器正确触发,只需在函数中关闭} 后添加一个()。如function GetLocList() { //some code here }();

标签: c# angularjs asp.net-mvc entity-framework


【解决方案1】:

所以这是在@Jax 帮助下的解决方案。我将 CustForm.js 文件更改为:-

 $scope.GetLocList = function () {
                $http({
                    method: 'Get',
                    url: '/Home/GetLocList'
                }).success(function (data, status, headers, config) {
                    $scope.location = data;
                }).error(function (data, status, headers, config) {
                    $scope.message = 'Unexpected Error';
                });
            }

            $scope.GetLocList();

不要忘记在 Angular 控制器中添加 $http。将我的 Html 更改为:-

 <select ng-model="CustLoc" ng-options="l.LocName for l in location track by l.Id">
                                <option value="">-- Select Country --</option>
                            </select>
                            <span class="error" ng-show="(f1.uCustLoc.$dirty || f1.$submitted) && f1.uCustLoc.$error.required">Location required!</span>

最后我的 C# 代码是:-

[HttpGet]
    public JsonResult GetLocList()
    {
        //IEnumerable<LocationTbl> ie = (from d in db.LocationTbls
        //                              select d).ToList();

        var ret = db.LocationTbls.Select(x => new { x.Id, x.LocName }).ToList();

        return Json(ret,JsonRequestBehavior.AllowGet);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多