利用DropDownList实现下拉
在视图的Model
一:实现下拉属性列表的写法
通过使用SelectListItem来自动填充到DropDownList中,形成下拉框。
我们想要在前台页面将数据变为下拉就要用到DropDownList这个特性标签来实现,但是使用的前提是要在Action里面进行设置,对Value和Text进行赋值。
下面是属性的写法,是IEnumerable<>接口类型
public class CreatCustomerView
{
public CreatCustomerView()
{
this.Schools = new List();
}
///
/// 外键
///
[Display(Name = "学校"), Required(ErrorMessage = "不能选择为空")]
public Guid SchoolId { get; set; }
///
/// 学校的导航属性
///
public IEnumerable Schools { get; set; }
///
/// OpenId:跟微信绑定的唯一表示,从微信处获取
///
public string OpenId { get; set; }
}
写成这样就是想将其Schools放在一个集合里面,而且在上面初始化的时候写成了SelectListItem。
SelectListItem代表System.Web.Mvc的实例的选择项。SelectList类。这里将在Action里面进行相关的设置。
IEnumerable
二:在Action里面的写法
这里就是为其Value和Text进行赋值。
public ActionResult ChooseSchool()
{
var entity = new CreatCustomerView();
entity.Schools = _schoolService.GetAll()
.Where(x => x.Id != Guid.Empty)
.Select(x => new SelectListItem
{
Text = x.Name,
Value = x.Id.ToString()
}).ToList();
return View(entity);
}
首先通过GetALL方法来取出数据库表中的数据,通过Select对其进行赋值,转换为ToList()的形式,在将其传到视图。这里就是为其里面赋值,为将来在前台页面进行Foreach做准备。
三:View视图里面的写法
在视图里面是通过HtmlHelper中的DropDownList来实现的,但是DropDownList的现实要通过下面的三个步奏来实现。
其实就是前面两个步奏中的内容,下面是View中的代码。
@{
ViewBag.Title = "选择学校";
Layout = "~/Views/Shared/_LayoutNew.cshtml";
}
@using System.Runtime.InteropServices
@model Express.Weixin.Web.Models.CreatCustomerView
返回选择学校
@using (Html.BeginForm(null, null, FormMethod.Post))
{
@Html.LabelFor(x => x.SchoolId)
@Html.DropDownListFor(x => x.SchoolId, Model.Schools, new { @class = "form-control" })
@Html.ValidationMessageFor(x => x.SchoolId)
}
通过里面的@Html.DropDownListFor(x => x.SchoolId, Model.Schools, new { @class = "form-control" }) 来实现下拉的结果。
四:显示结果
附件:DropDownList知识参考资料 http://www.cnblogs.com/kirinboy/archive/2009/10/28/use-dropdownlist-in-asp-net-mvc.html