MVC创建通用DropdownList
起因
MVC项目中有数据字典表,定义了多个类型,需要给每个类型做下拉菜单。
不可能每个类型,都敲一个代码,需要做成通用
思路
- 利用MVC的部件方式,分别定义Controller,View和Model;
- Model的字段需要有:控件名称(WidgetName),数据字典类型(TypeName),选中的值(SelectedValue),数据集(SelectListItems)。需要根据数据字典类型去数据库表中过滤需要的类型,放入数据集中;
- View为部分页,Layout=null。
实现
1.Controller定义方法
public virtual ActionResult GetDropdownList(string widgetName, string selectedValue, string typeName)
{
DropdownListModel model = new DropdownListModel();
model.SelectedValue = selectedValue;
model.WidgetName = widgetName;
model.TypeName = typeName;
return View(model);
}
2.Model
public class DropdownListModel
{
/// <summary>
///选中值
/// </summary>
public string SelectedValue;
/// <summary>
/// 控件名称
/// </summary>
public string WidgetName;
/// <summary>
/// 值类型
/// </summary>
public string TypeName;
/// <summary>
/// 状态列表SelectListItems
/// </summary>
public IList<SelectListItem> StateSelectListItems
{
get
{
IList<SelectListItem> selectListItems = new List<SelectListItem>();
IEnumerable<AttrInfo> attrList = WMFactory.Attr.FindByConditions(null, f => f.Code == TypeName);
if (attrList.Count() > 0)
{
Guid attrId = attrList.First().Id;
IEnumerable<AttrEnumInfo> enumList = WMFactory.AttrEnum.FindByConditions(null, f => f.AttrId == attrId);
foreach (AttrEnumInfo attrEnum in enumList)
{
SelectListItem selectListItem = new SelectListItem();
selectListItem.Value = attrEnum.AttrValue;
selectListItem.Text = attrEnum.AttrText;
selectListItems.Add(selectListItem);
}
}
return selectListItems;
}
}
}
3.View
@{
Layout = null;
}
@model ZPS.FX.CRM.WebUI.Areas.ManageCenter.Models.Common.ProductTypeDropdownListModel
@if (!string.IsNullOrEmpty(Model.WidgetName))
{
//指定控件名称
@Html.DropDownListFor(m => m.SelectedValue, Model.StateSelectListItems, new { @id = Model.WidgetName, @Name = Model.WidgetName.Replace("_", "."), @class = "form-control" })
}
else
{
//没有指定控件名称
@Html.DropDownListFor(m => m.SelectedValue, Model.StateSelectListItems, new { @class = "form-control" })
}
使用方式
<div class="col-sm-4">
@Html.Action("GetDropdownList", "Common", new { widgetName = "BizDistrict_Type", selectedValue = (Model == null || Model.BizDistrict == null) ? "" : Model.BizDistrict.Type, typeName = "BizDistrictType" })
</div>