今天使用angularjs的ng-options实现一个DropDownList下拉列表。
准备ASP.NET MVC的model:
public class MobilePhone { public int ID { get; set; } public string Name { get; set; } }
接下来,还得准备Entity:
public IEnumerableMobilePhones() { return new List () { { new MobilePhone() { ID = 1, Name = "华为" }}, { new MobilePhone() { ID = 2, Name = "苹果" }}, { new MobilePhone() { ID = 3, Name = "小米" }}, { new MobilePhone() { ID = 4, Name = "中兴" }} }; } }
创建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); } }
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; }); }]);
不管是ASP.NET MVC还是AngularJs程序代码均准备好,现在我们需要在ASP.NET MVC视图实现下拉列表:
@{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml";}
上面有句ng-options绑定的表达式中,名词所来自何处,可参考下图指示:
动态效果演示: