在DropDownListFor中使用枚举值

时间:2013-12-19 14:58:55

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

这是我的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
}

这是我在Controller中的Create Action:

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>   

我正在使用您可以找到的here

但是现在我总是在我的创建视图中对此规则中出现此错误:

@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&gt;,System.Collections。 Generic.IEnumerable,string)'和'System.Web.Mvc.Html.SelectExtensions.DropDownListFor(System.Web.Mvc.HtmlHelper,System.Linq.Expressions.Expression&gt;,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

3 个答案:

答案 0 :(得分: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>();

答案 1 :(得分:1)

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

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)

答案 2 :(得分:0)

如果你想为这个视图快速解决方法,你可以做这样的事情。虽然建议使用哈立德的方法。

 <select id = 'myenumdropdown' class='something'>

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

 </select>