您的位置:首页 > 运维架构

MVC DropDownListFor 的使用和无限级分类的展示

2014-04-02 14:41 197 查看
先说一下SelectList类: 表示一个列表

构造函数1:SelectList(IEnumerable)使用列表的指定项来初始化SelectList
类的新实例。

构造函数2:SelectList(IEnumerable, Object) 使用列表的指定项和选定的值来初始化SelectList
类的新实例。

构造函数3:SelectList(IEnumerable, String, String)使用列表的指定项、数据值字段和数据文本字段来初始化SelectList
类的新实例。

构造函数4:SelectList(IEnumerable, String, String, Object)使用列表的指定项、数据值字段、数据文本字段和选定的值来初始化新实例。

使用方法1:直接写在html中的

@Html.DropDownListFor(m => m.proType, new[]{new SelectListItem(){Text="--请选择--",Value=""},new SelectListItem(){Text="1",Value="1"}}, new{ @id="ddl",@class="cssClass"})


使用方法2:动态添加的

(1):获取列表项

public static SelectList GetSelectList()
{
List<SelectListItem> l = new List<SelectListItem>();
for (int i = 0; i < 10; i++)
{
SelectListItem sli = new SelectListItem() { Text = i.ToString(), Value = i.ToString() };
l.Add(sli);
}
SelectList sl = new SelectList(l, "Value", "Text");
return sl;

}
(2)把列表项传递过去

ViewBag.ddl = GetSelectList();
(3)在视图中,把列表项遍历出来

@Html.DropDownListFor(m => m.proType, ViewBag.ddl as SelectList, new{ @id="ddl",@class="cssClass"})


无限级分类展示:

如果有一个类别表,是无限级分类的 我们假设 表名: Type 列: id(主键) name(名称) fid(父ID). 如果fid为0或null,说明没有父级项.我们如何使用

Html.DropDownListFor(...)把它分层次的展示出来.形如下图:



第一步:获取数据(当前这获取数据种方式为了例子而例子.效率很低....建议使用存储过程)

/// <summary>
/// 获取要显示的内容
/// </summary>
/// <param name="fid">父ID</param>
/// <returns>List<Type> 类别对列表</returns>
public List<Type> GetClassList(int fid = 0)
{
List<Type> l = new List<Type>();
DCDataContext dc = new DCDataContext();
var rs = dc.Type.Where(r => r.fId == fid);
if (rs.Count() > 0)
{
int deep = 1;
foreach (Type t in rs)
{
//获取深度
deep = GetDeep(t.id);
//拼接显示的形式
string line = "├("+deep+")";
string space ="";
for (int i = 1; i < deep; i++)
{
space += HttpUtility.HtmlDecode("   ");
}
t.name = space + line + t.name;
//把查询的对象添加到列表中
l.Add(t);
l.AddRange(GetClassList(t.id));
//把深度值初始化
deep = 1;
}
}
return l;
}

/// <summary>
/// 获取指定对象的深度
/// </summary>
/// <param name="id">对象ID</param>
/// <returns>深度</returns>
private int GetDeep(int id)
{
int deep=1;
DCDataContext dc = new DCDataContext();
Type t = dc.Type.Where(r => r.id == id).FirstOrDefault();
if (t != null)
{
if (t.fId == null || t.fId == 0)
{
return deep;
}
else
{
deep+=GetDeep((int)t.fId);
}
}
else
{
return deep;

}
return deep;
}


第二步:调用数据

public ActionResult Index()
{
ViewBag.classList = GetClassList(0);
return View();
}


第三部:视图中显示

@Html.DropDownListFor(m => m.id, new SelectList(@ViewBag.ClassList, "Id", "Name"), new { })
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: