DropDownListFor使用ViewData进行绑定的示例
特别注意,经实践:
此方法的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>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)