@Html.DropDownListFor 綁定列表項


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;
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM