今天使用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 class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="~/Angularjs/app.js"></script><script class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="~/Angularjs/PhoneController.js"></script>
Source Code
上面有句ng-options绑定的表达式中,名词所来自何处,可参考下图指示:
动态效果演示:
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦