welcome to Qijie's Blog 薛其杰

MVC中为 DropDownListFor 绑定列表项, 一种方案从后台加载列表内容,通过ViewData传递到前台页面.

View:

        <div class="editor-label">
            @Html.LabelFor(model => model.CategoryType)
        </div>
        <div class="editor-field">
            @Html.DropDownListFor(model => model.CategoryType, ViewData["Type"] as SelectList)
            @Html.ValidationMessageFor(model=>model.CategoryType)
        </div>


Code:

        public ActionResult Create()
        {
            ViewData["Type"] = GenerateList();
            return View();
        }

        public static SelectList GenerateList()
        {
            List<SelectListItem> items = new List<SelectListItem>()
            {
                new SelectListItem(){Text="Income", Value="income"},
                new SelectListItem(){Text="Outcome", Value="outcome"}
            };

            SelectList generateList = new SelectList(items, "Value", "Text");

            return generateList;
        }

 

posted on 2014-03-18 14:28  零点零一  阅读(13772)  评论(0编辑  收藏  举报