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>

 

posted on   itjeff  阅读(457)  评论(0编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示