• 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>

  • 相关阅读:
    (参考)爬虫5-爬取中国大学排名情况
    005_软件安装之_常用办公软件
    004_软件安装之_Altium Designer
    001_基础硬件电路_二极管
    添加QQ群
    024_STM32程序移植之_ESP8266_TCP
    020_C语言常用函数
    004——转载C#禁止改变窗体大小
    003转载----C#打开网页
    002_Python基础学习网站
  • 原文地址:https://www.cnblogs.com/itjeff/p/4935221.html
Copyright © 2020-2023  润新知