特别注意,经实践:
此方法的ViewBag的名称必须和new SelectList()中的最后一个参数,即下拉框的默认值的名称必须相同,如:
ViewBag.Title = WebConst.UnSelect.Union(new SelectList(WebConst.Dictionary.Where(p => p.Category == "Title").OrderBy(p => p.Sort), "Value", "Display", item.Title));
ViewBag.Title的Title必须和
new SelectList(WebConst.Dictionary.Where(p => p.Category == "Title").OrderBy(p => p.Sort), "Value", "Display", item.Title)
中的item.Title 的Title名字相同,也必须和前台中的
@Html.DropDownListFor(p => p.Title, ViewBag.Title as SelectList, new { @class = "selOp" })的p.Title相同,
否则可能会出现错误,需要特别注意。
另外,如果需要用js向select添加第一项option,如请选择等项,可以使用:
$("selectid").prepend("<option value=''>请选择</option>");
public readonly static IList<SelectListItem> UnSelect = new List<SelectListItem>
{
new SelectListItem{Text="请选择",Value=""},
};
public readonly static IList<SelectListItem> YesNo = new List<SelectListItem>
{
new SelectListItem { Text ="否" , Value = "false"},
new SelectListItem { Text ="是" , Value = "true"},
};
ViewBag.PurchaseLimited = WebConst.UnSelect.Union(new SelectList(WebConst.YesNo, "Value", "Text", item.PurchaseLimited));
ViewBag.AcceptPromotionInfo = WebConst.UnSelect.Union(new SelectList(WebConst.YesNo, "Value", "Text", item.AcceptPromotionInfo));
ViewBag.Title = WebConst.UnSelect.Union(new SelectList(WebConst.Dictionary.Where(p => p.Category == "Title").OrderBy(p => p.Sort), "Value", "Display", item.Title));
ViewBag.AgeRange = WebConst.UnSelect.Union(new SelectList(WebConst.Dictionary.Where(p => p.Category == "AgeRange").OrderBy(p => p.Sort), "Value", "Display", item.AgeRange));
//前台使用
<li>
<label class="required" for="Title">称谓</label>
<div class="selectArea selectArea2 mln5">
<span class="selectedItem">选择</span>
@Html.DropDownListFor(p => p.Title, ViewBag.Title as SelectList, new { @class = "selOp" })
<em></em>
</div>
</li>
<li>
<label>婚否</label>
<div class="selectArea selectArea2 mln5">
<span class="selectedItem">选择</span>
@Html.DropDownListFor(p => p.MaritalStatus, ViewBag.MaritalStatus as SelectList, new { @class = "selOp" })
<em></em>
</div>
</li>