【问题标题】:Use Enum Values in DropDownListFor在 DropDownListFor 中使用枚举值
【发布时间】:2013-12-19 14:58:54
【问题描述】:

这是我的 ViewModel:

public class EntityViewModel
{
    [Required(ErrorMessage = "Title is required")]
    [StringLength(255)]
    [DisplayName("Title")]
    public string Title { get; set; }
    [Required(ErrorMessage = "Description is required")]
    [DisplayName("Description")]
    public string Description { get; set; }
    [Required]
    public DateTime StartTime { get; set; }
    [Required]
    public DateTime EndTime { get; set; }

    [Required]
    public Decimal InstantSellingPrice { get; set; }
    public Nullable<Decimal> ShippingPrice { get; set; }
    public Int64 Views { get; set; }

    public Int32 UserId { get; set; }

    public int RegionId { get; set; }

    public short SelectCategoryId { get; set; }
    public SelectList Categories { get; set; }

    public IEnumerable<HttpPostedFileBase> Files { get; set; }

    public Condition? Condition { get; set; }
}

public enum Condition
{
    New=1,
    Used=2
}

这是我在控制器中的创建操作:

public ActionResult Create()
{
    ViewBag.DropDownList = ReUzze.Helpers.EnumHelper.SelectListFor<Condition>();

    var model = new ReUzze.Models.EntityViewModel
    {
        Categories = new SelectList(this.UnitOfWork.CategoryRepository.Get(), "Id", "Name")
    };
    return View(model);
  }

在我的创建视图中:

<div class="form-group">
    @Html.LabelFor(model => model.Condition)
    @Html.DropDownListFor(model => model.Condition, ViewBag.DropDownList as SelectList, null)
</div>   

我正在使用 Enumhelper,您可以找到 here

但是现在我总是在我的 Create View 中遇到这个错误:

@Html.DropDownListFor(model => model.Condition, ViewBag.DropDownList as SelectList, null)

错误:

错误 1 ​​以下方法或属性之间的调用不明确:'System.Web.Mvc.Html.SelectExtensions.DropDownListFor(System.Web.Mvc.HtmlHelper, System.Linq.Expressions.Expression>, System.Collections. Generic.IEnumerable,字符串)'和'System.Web.Mvc.Html.SelectExtensions.DropDownListFor(System.Web.Mvc.HtmlHelper,System.Linq.Expressions.Expression>,System.Collections.Generic.IEnumerable,System.Collections。 Generic.IDictionary)' c:\Users\Niels\Documents\Visual Studio 2012\Projects\ReUzze\ReUzze\Views\Entity\Create.cshtml 57 30 ReUzze

【问题讨论】:

    标签: mysql asp.net-mvc asp.net-mvc-4 razor enums


    【解决方案1】:

    我通常使用这样的代码。

    public static class Enums {
    
        public static IList<SelectListItem> SelectListOf<TEnum>(bool empty = false)
        {
            var type = typeof(TEnum);
            if (type.IsEnum)
            {
                var list = Enum.GetValues(type)
                    .Cast<TEnum>()
                    .OrderBy(x => x)
                    .Select(x => new SelectListItem { Text = GetDescription(x), Value = x.ToString() })
                    .ToList();
    
                if (empty)
                {
                    list.Insert(0, new SelectListItem());
                }
    
                return list;
    
            }
    
            return new List<SelectListItem>();
        }
    
        private static string GetDescription(object enumerator)
        {
            try
            {
                //get the enumerator type
                Type type = enumerator.GetType();
    
                //get the member info
                MemberInfo[] memberInfo = type.GetMember(enumerator.ToString());
    
                //if there is member information
                if (memberInfo != null && memberInfo.Length > 0)
                {
                    //we default to the first member info, as it's for the specific enum value
                    object[] attributes = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
    
                    //return the description if it's found
                    if (attributes != null && attributes.Length > 0)
                        return ((DescriptionAttribute)attributes[0]).Description;
                }
    
                //if there's no description, return the string value of the enum
                return enumerator.ToString();
            }
            catch (Exception e)
            {
                return string.Empty;
            }
        }
    
    }
    

    那么你可以这样使用它:

    Conditions = Enums.SelectListOf<Condition>();
    

    【讨论】:

    • 您能提供更多信息吗?因为我不明白这个..我在我的模型中使用它吗?
    • 是的,您可以在视图模型的构造函数中使用它,也可以直接在视图中使用它。
    【解决方案2】:

    查看我关于这个主题的博文。

    http://jnye.co/Posts/4/creating-a-dropdown-list-from-an-enum-in-mvc-and-c%23

    这是我使用的一个枚举助手,它可以将枚举转换为一个选择列表。注意:如果枚举有描述(使用DescriptionAttribute),它将使用它作为显示文本

    public static class EnumHelper
    {
        // Get the value of the description attribute if the   
        // enum has one, otherwise use the value.  
        public static string GetDescription<TEnum>(this TEnum value)
        {
            var fi = value.GetType().GetField(value.ToString());
    
            if (fi != null)
            {
                var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
    
                if (attributes.Length > 0)
                {
                    return attributes[0].Description;
                }
            }
    
            return value.ToString();
        }
    
        /// <summary>
        /// Build a select list for an enum
        /// </summary>
        public static SelectList SelectListFor<T>() where T : struct
        {
            Type t = typeof(T);
            return !t.IsEnum ? null
                             : new SelectList(BuildSelectListItems(t), "Value", "Text");
        }
    
        /// <summary>
        /// Build a select list for an enum with a particular value selected 
        /// </summary>
        public static SelectList SelectListFor<T>(T selected) where T : struct
        {
            Type t = typeof(T);
            return !t.IsEnum ? null
                             : new SelectList(BuildSelectListItems(t), "Value", "Text", selected.ToString());
        }
    
        private static IEnumerable<SelectListItem> BuildSelectListItems(Type t)
        {
            return Enum.GetValues(t)
                       .Cast<Enum>()
                       .Select(e => new SelectListItem { Value = e.ToString(), Text = e.GetDescription() });
        }
    }
    

    一旦你有了这个帮助类,你就可以执行以下操作。

    在您的控制器中:

    //If you don't have an enum value use the type
    ViewBag.DropDownList = EnumHelper.SelectListFor<MyEnum>();
    
    //If you do have an enum value use the value (the value will be marked as selected)    
    ViewBag.DropDownList = EnumHelper.SelectListFor(MyEnum.MyEnumValue);
    

    在你看来:

    @Html.DropDownList("DropDownList")
    @* OR *@
    @Html.DropDownListFor(m => m.Property, ViewBag.DropDownList as SelectList, null)
    

    【讨论】:

    • 谢谢,Model中的Propery是怎么定义的?
    • 是的,“属性”是您正在为其创建下拉列表的视图模型的属性。它还提供了选定的值
    • 像这样: public int ConditionId { get;放; ??当我这样做时,我得到一个巨大的错误
    • 更新了我的开始帖子以更清晰。
    • DropDownListFor 中删除最后一个null 参数或替换为您要选择的值的字符串
    【解决方案3】:

    如果您只想针对这一视图快速解决问题,您可以执行以下操作。虽然推荐使用 Khalid 的方法。

     <select id = 'myenumdropdown' class='something'>
    
        @foreach(var item in Enum.GetValues(typeof('yourenumtype')))
        {
          <option value=item.ToHashCode()>item.ToString()</option>
        }
    
     </select>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多