• Bind Enum To DropDownList ?


    0. 准备测试数据

    0.1 : 枚举

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace MvcApplication.Models
    {
        public enum YesOrNo
        {
            否 = 0,
            是 = 1
        }
    }
    

    0.2 : 对应实体类及表sql

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.ComponentModel.DataAnnotations;
    
    namespace MvcApplication.Models
    {
        public class Test
        {
            [Key]
            public int Id { get; set; }
    
            [Display(Name = "状态")]
            [Required(ErrorMessage = "状态不能为空.")]
            public int Status { get; set; }
        }
    }
    
    /*
    -- 对应SQL
     CREATE TABLE Test(
        Id INT PRIMARY KEY IDENTITY(1,1),
        [Status] INT
    )
    go
    INSERT INTO Test VALUES(1)
     */

    0.3 在Controller 文件夹上生成强类型(Test)的读写控制器及视图. (自动生成这些,我们的测试工作就很轻松了)

    1.  写一个扩展方法,放在静态的工具类中。

    /// <summary>
    /// 将枚举转换到Select的扩展方法
    /// </summary>
    /// <typeparam name="TEnum">枚举类型</typeparam>
    /// <param name="enumObj">枚举对象</param>
    /// <returns>SelectList</returns>
    public static SelectList ToSelectList<TEnum>(this TEnum enumObj)
    {
        var values = from TEnum e in Enum.GetValues(typeof(TEnum))
                        select new { Id = Convert.ToInt32(e), Name = e.ToString() };
    
        return new SelectList(values, "Id", "Name", Convert.ToInt32(enumObj));
    }
    
     
    

    2. 改写Action

    //
    // GET: /Test/Edit/1
     
    public ActionResult Edit(int id)
    {
        Test test = db.Test.Find(id);
        ViewBag.list = ((YesOrNo)test.Status).ToSelectList();
        //ViewData["status"] = ((YesOrNo)test.Status).ToSelectList();  //不可以的
        return View(test);
    }
    

    3. 改写View 中的Edit.cshtml

    @Html.DropDownListFor(model=> model.Status, ViewBag.list as SelectList )

    本文转自:http://blog.csdn.net/yenange/article/details/8847833

  • 相关阅读:
    I
    D
    K
    G
    J
    Doom HDU
    Mountaineers Gym
    华南理工大学“三七互娱杯”程序设计竞赛(重现赛)( HRY and array 高精度除法模板)
    Corn Fields POJ
    linux如何安装缺失依赖
  • 原文地址:https://www.cnblogs.com/dacheng/p/3148408.html
Copyright © 2020-2023  润新知