ASP.NET MVC下使用AngularJs語言(三):ng-options

Insus.NET發表於2018-03-08

今天使用angularjs的ng-options實現一個DropDownList下拉選單。

準備ASP.NET MVC的model:

 

 public class MobilePhone
    {
        public int ID { get; set; }

        public string Name { get; set; }
    }
Source Code

 

接下來,還得準備Entity:

 

 public IEnumerable<MobilePhone> MobilePhones()
        {
            return new List<MobilePhone>()
            {
                {new MobilePhone() { ID = 1, Name = "華為" }},
                {new MobilePhone() { ID = 2, Name = "蘋果" }},
                {new MobilePhone() { ID = 3, Name = "小米" }},
                {new MobilePhone() { ID = 4, Name = "中興" }}
            };
        }
    }
Source Code

 

建立ASP.NET MVC的Controller,一個是檢視Action,另一個是資料Action:



 public class PhoneController : Controller
    {
        // GET: Phone
        public ActionResult Index()
        {
            return View();
        }

        public JsonResult GetMobilePhones()
        {
            MobilePhoneEntity mpe = new MobilePhoneEntity();
            var model = mpe.MobilePhones();
            return Json(model, JsonRequestBehavior.AllowGet);
        }
    }
Source Code


最後,我們需要準備一個angularjs的Controller:


pilotApp.controller('PhoneCtrl', ['$http', '$location', '$rootScope', '$scope',
    function ($http, $location, $rootScope, $scope) {
        var obj = {};

        $http({
            method: 'POST',
            url: '/Phone/GetMobilePhones',
            dataType: 'json',
            headers: {
                'Content-Type': 'application/json; charset=utf-8'
            },
            data: JSON.stringify(obj),
        }).then(function (response) {
            $scope.Phones = response.data;
        });

    }]
);
Source Code

 

不管是ASP.NET MVC還是AngularJs程式程式碼均準備好,現在我們需要在ASP.NET MVC檢視實現下拉選單:

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}


<div ng-app="PilotApp" ng-controller="PhoneCtrl">
    <select ng-model="ddlPhones" ng-options="MobilePhone.Name for MobilePhone in Phones"></select>
</div>

<script src="~/Angularjs/app.js"></script>
<script src="~/Angularjs/PhoneController.js"></script>
Source Code

 

 

上面有句ng-options繫結的表示式中,名詞所來自何處,可參考下圖指示:

 

 

動態效果演示:

 

 

相關文章