MVC3 Razor DropDownListFor Enums


84

Projemi MVC3'e güncellemeye çalışıyorum, bulamadığım bir şey:

Basit bir ENUMS veri türüne sahibim:

public enum States()
{
  AL,AK,AZ,...WY
}

Bu veri türünü içeren bir model görünümümde DropDown / SelectList olarak kullanmak istediğim:

public class FormModel()
{
    public States State {get; set;}
}

Oldukça basit: Bu kısmi sınıf için otomatik oluşturma görünümünü kullanmaya gittiğimde, bu türü yok sayıyor.

AJAX - JSON POST Metodu ile gönder düğmesine bastığımda ve işlediğimde enum değerini seçilen öğe olarak ayarlayan basit bir seçim listesine ihtiyacım var.

Ve görünümden (???!):

    <div class="editor-field">
        @Html.DropDownListFor(model => model.State, model => model.States)
    </div>

tavsiye için şimdiden teşekkürler!


8
Bu iş parçacığıyla karşılaşan ve MVC 5.1 veya üstünü kullanan herkes için, Html.EnumDropDownListFor () yardımcı yöntemi artık MVC'de yerleşiktir - bkz. Asp.net/mvc/overview/releases/mvc51-release-notes
mecsco

Yanıtlar:


55

Kendi projem için bir tane yaptım. Aşağıdaki kod yardımcı sınıfımın bir parçasıdır, umarım gerekli tüm yöntemleri almışımdır. Çalışmazsa bir yorum yazın, tekrar kontrol edeceğim.

public static class SelectExtensions
{

    public static string GetInputName<TModel, TProperty>(Expression<Func<TModel, TProperty>> expression)
    {
        if (expression.Body.NodeType == ExpressionType.Call)
        {
            MethodCallExpression methodCallExpression = (MethodCallExpression)expression.Body;
            string name = GetInputName(methodCallExpression);
            return name.Substring(expression.Parameters[0].Name.Length + 1);

        }
        return expression.Body.ToString().Substring(expression.Parameters[0].Name.Length + 1);
    }

    private static string GetInputName(MethodCallExpression expression)
    {
        // p => p.Foo.Bar().Baz.ToString() => p.Foo OR throw...
        MethodCallExpression methodCallExpression = expression.Object as MethodCallExpression;
        if (methodCallExpression != null)
        {
            return GetInputName(methodCallExpression);
        }
        return expression.Object.ToString();
    }

    public static MvcHtmlString EnumDropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression) where TModel : class
    {
        string inputName = GetInputName(expression);
        var value = htmlHelper.ViewData.Model == null
            ? default(TProperty)
            : expression.Compile()(htmlHelper.ViewData.Model);

        return htmlHelper.DropDownList(inputName, ToSelectList(typeof(TProperty), value.ToString()));
    }

    public static SelectList ToSelectList(Type enumType, string selectedItem)
    {
        List<SelectListItem> items = new List<SelectListItem>();
        foreach (var item in Enum.GetValues(enumType))
        {
            FieldInfo fi = enumType.GetField(item.ToString());
            var attribute = fi.GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault();
            var title = attribute == null ? item.ToString() : ((DescriptionAttribute)attribute).Description;
            var listItem = new SelectListItem
                {
                    Value = ((int)item).ToString(),
                    Text = title,
                    Selected = selectedItem == ((int)item).ToString()
                };
            items.Add(listItem);
        }

        return new SelectList(items, "Value", "Text", selectedItem);
    }
}

Şu şekilde kullanın:

Html.EnumDropDownListFor(m => m.YourEnum);

Güncelleme

Alternatif Html Yardımcıları oluşturdum. Bunları kullanmak için yapmanız gereken tek şey, içindeki ana görüntü sayfanızı değiştirmektir views\web.config.

Onlarla şunları yapabilirsiniz:

@Html2.DropDownFor(m => m.YourEnum);
@Html2.CheckboxesFor(m => m.YourEnum);
@Html2.RadioButtonsFor(m => m.YourEnum);

Daha fazla bilgi burada: http://blog.gauffin.org/2011/10/first-draft-of-my-alternative-html-helpers/


1
Tamam, her iki şekilde de çalışıyor, sadece bir derleme hatası alıyorum: Satır 41: return htmlHelper.DropDownList (inputName, ToSelectList (typeof (TProperty), value.ToString ())); 'System.Web.Mvc.HtmlHelper <TModel>', 'DropDownList' için bir tanım içermez ve 'System.Web.Mvc.HtmlHelper <TModel>' türündeki ilk bağımsız değişkeni kabul eden 'DropDownList' uzantı yöntemi bulunmaz ( bir kullanma yönergesi veya bir derleme başvurusu eksik mi?)
jordan.baucke

1
@jordan Bende de aynı hata var. Sorunu çözmeyi başardınız mı?
SF Developer

9
@filu eklemek @jordan using System.Web.Mvc.Html;erişmeniz gereken olarakSelectExtensionsClass
Simon Hartcher

3
@Para Aynı sorunu alıyorum, seçilen değer Görünümde seçili görünmüyor. (Ben değiştirmek zorunda ((int)item).ToString()için Enum.GetName(enumType, item)almak için SelectListItemdoğru seçilmiş olarak kaydedilir, ama yine de işi değil)
Fernando Neira

1
Aşağıya seçim konusunu kapsayan bir cevap ekledik - DropDownList aşırı yüklemelerinin davranışlarının yanlış anlaşılmasından kaynaklanıyor.
Jon Egerton

199

Burada bunun için daha basit bir çözüm buldum: http://coding-in.net/asp-net-mvc-3-method-extension/

using System;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;

namespace EnumHtmlHelper.Helper
{    
    public static class EnumDropDownList
    {
        public static HtmlString EnumDropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> modelExpression, string firstElement)
        {
            var typeOfProperty = modelExpression.ReturnType;
            if(!typeOfProperty.IsEnum)
                throw new ArgumentException(string.Format("Type {0} is not an enum", typeOfProperty));     
            var enumValues = new SelectList(Enum.GetValues(typeOfProperty));
            return htmlHelper.DropDownListFor(modelExpression, enumValues, firstElement);
}   }   }

Jiletteki bir satır bunu yapacak:

@Html.DropDownListFor(model => model.State, new SelectList(Enum.GetValues(typeof(MyNamespace.Enums.States))))

Bağlantılı makalede bir uzantı yöntemiyle bunu yapmak için kod da bulabilirsiniz.


6
Bunun çözüm olarak işaretlenmesi gerektiğini düşünüyorum. En iyisi, karmaşıklıkla değil basitlikle işaretlenir.
Lord of Scripts

3
DropDowList sürümüne bakanlar için (benim gibi): @ Html.DropDownList ("listName", new SelectList (Enum.GetValues ​​(typeof (MyNamespace.Enums.States))))
dstr

2
@JonEgerton Eğer benimle aynı şeyi kastediyorsan, o zaman katılıyorum. Numaralandırma + açıklama + bir görüntüyü göstermek istiyorsanız, Mike McLaughlin'in çözümüyle kaybolursunuz.
Elisabeth

1
Bu çözümlerle bulduğum tek sorun, seçilen değeri yüklerken doğru şekilde eşleştirmemesidir. Bunun dışında oldukça iyi.
triangulito

3
@triangulito bu hiç sorun değil :)@Html.DropDownListFor(model => model.State, new SelectList(Enum.GetValues(typeof(MyNamespace.Enums.States)),model.State))
VladL


17

Gerçekten basit bir şey istiyorsanız, durumu veritabanında nasıl sakladığınıza bağlı olarak başka bir yol var.

Böyle bir varlığınız varsa:

public class Address
{
     //other address fields

     //this is what the state gets stored as in the db
     public byte StateCode { get; set; }

     //this maps our db field to an enum
     public States State
     {
         get
         {
             return (States)StateCode;
         }
         set
         {
             StateCode = (byte)value;
         }
     }
}

Ardından açılır listeyi oluşturmak şu kadar kolay olacaktır:

@Html.DropDownListFor(x => x.StateCode,
    from State state in Enum.GetValues(typeof(States))
    select new SelectListItem() { Text = state.ToString(), Value = ((int)state).ToString() }
);

LINQ güzel değil mi?


Model veya Görünümde Durumlar numaralandırmasını nerede tanımlarsınız?
superartsy

model sınıfında kullanıldığı gibi
sjmeverett

1
@stewartml ViewModel'im enum özelliğine + "SelectedCodeProperty" ye sahipse, bu, yazınızdaki bir özellik çok fazladır. Neden her ikisinde de seçilen değer olarak numaralandırmanın sunucuya + öğe değeri olarak geri gönderilmesine sahip değilsiniz?
Elisabeth

13

Bunu tek seferde yapabildim.

@Html.DropDownListFor(m=>m.YourModelProperty,new SelectList(Enum.GetValues(typeof(YourEnumType))))

8

@Jgauffin tarafından kabul edilen yanıta dayanarak, EnumDropDownListForöğe seçme sorunuyla ilgilenen kendi sürümümü oluşturdum .

Sorun burada başka bir SO cevabında ayrıntılı olarak açıklanmıştır : ve temelde farklı aşırı yüklerin davranışının yanlış anlaşılmasına bağlıdır DropDownList.

Tam kodum ( htmlAttributesvb. İçin aşırı yüklemeleri içerir :

public static class EnumDropDownListForHelper
{

    public static MvcHtmlString EnumDropDownListFor<TModel, TProperty>(
            this HtmlHelper<TModel> htmlHelper, 
            Expression<Func<TModel, TProperty>> expression
        ) where TModel : class
    {
        return EnumDropDownListFor<TModel, TProperty>(
                            htmlHelper, expression, null, null);
    }

    public static MvcHtmlString EnumDropDownListFor<TModel, TProperty>(
            this HtmlHelper<TModel> htmlHelper, 
            Expression<Func<TModel, TProperty>> expression, 
            object htmlAttributes
        ) where TModel : class
    {
        return EnumDropDownListFor<TModel, TProperty>(
                            htmlHelper, expression, null, htmlAttributes);
    }

    public static MvcHtmlString EnumDropDownListFor<TModel, TProperty>(
            this HtmlHelper<TModel> htmlHelper, 
            Expression<Func<TModel, TProperty>> expression, 
            IDictionary<string, object> htmlAttributes
        ) where TModel : class
    {
        return EnumDropDownListFor<TModel, TProperty>(
                            htmlHelper, expression, null, htmlAttributes);
    }

    public static MvcHtmlString EnumDropDownListFor<TModel, TProperty>(
            this HtmlHelper<TModel> htmlHelper, 
            Expression<Func<TModel, TProperty>> expression, 
            string optionLabel
        ) where TModel : class
    {
        return EnumDropDownListFor<TModel, TProperty>(
                            htmlHelper, expression, optionLabel, null);
    }

    public static MvcHtmlString EnumDropDownListFor<TModel, TProperty>(
            this HtmlHelper<TModel> htmlHelper, 
            Expression<Func<TModel, TProperty>> expression, 
            string optionLabel, 
            IDictionary<string,object> htmlAttributes
        ) where TModel : class
    {
        string inputName = GetInputName(expression);
        return htmlHelper.DropDownList(
                            inputName, ToSelectList(typeof(TProperty)), 
                            optionLabel, htmlAttributes);
    }

    public static MvcHtmlString EnumDropDownListFor<TModel, TProperty>(
            this HtmlHelper<TModel> htmlHelper, 
            Expression<Func<TModel, TProperty>> expression, 
            string optionLabel, 
            object htmlAttributes
        ) where TModel : class
    {
        string inputName = GetInputName(expression);
        return htmlHelper.DropDownList(
                            inputName, ToSelectList(typeof(TProperty)), 
                            optionLabel, htmlAttributes);
    }


    private static string GetInputName<TModel, TProperty>(
            Expression<Func<TModel, TProperty>> expression)
    {
        if (expression.Body.NodeType == ExpressionType.Call)
        {
            MethodCallExpression methodCallExpression 
                            = (MethodCallExpression)expression.Body;
            string name = GetInputName(methodCallExpression);
            return name.Substring(expression.Parameters[0].Name.Length + 1);

        }
        return expression.Body.ToString()
                    .Substring(expression.Parameters[0].Name.Length + 1);
    }

    private static string GetInputName(MethodCallExpression expression)
    {
        // p => p.Foo.Bar().Baz.ToString() => p.Foo OR throw...
        MethodCallExpression methodCallExpression 
                            = expression.Object as MethodCallExpression;
        if (methodCallExpression != null)
        {
            return GetInputName(methodCallExpression);
        }
        return expression.Object.ToString();
    }


    private static SelectList ToSelectList(Type enumType)
    {
        List<SelectListItem> items = new List<SelectListItem>();
        foreach (var item in Enum.GetValues(enumType))
        {
            FieldInfo fi = enumType.GetField(item.ToString());
            var attribute = fi.GetCustomAttributes(
                                       typeof(DescriptionAttribute), true)
                                  .FirstOrDefault();
            var title = attribute == null ? item.ToString() 
                              : ((DescriptionAttribute)attribute).Description;
            var listItem = new SelectListItem
            {
                Value = item.ToString(),
                Text = title,
            };
            items.Add(listItem);
        }

        return new SelectList(items, "Value", "Text");
    }
}

Bunu buradaki bloguma yazdım .


1
Numaram için uygun değeri doğru bir şekilde önceden seçen karşılaştığım tek çözüm bu. Teşekkürler!
Edwin Groenendaal

Harika. Bu kesinlikle kabul edilen cevap olmalıdır - işe yarıyor; kabul edilen cevap değil.
neminem

3

Bu, enum'dan bir int değeri seçerken yardımcı olacaktır: İşte SpecTypebir intalan ... ve enmSpecTypebir enum.

@Html.DropDownList(
    "SpecType", 
     YourNameSpace.SelectExtensions.ToSelectList(typeof(NREticaret.Core.Enums.enmSpecType), 
     Model.SpecType.ToString()), "Tip Seçiniz", new 
     { 
         gtbfieldid = "33", 
         @class = "small" 
     })

3

Benim için biraz daha iyi çalışmasını sağlamak için SelectList yönteminde aşağıdaki değişikliği yaptım. Belki başkaları için faydalı olacaktır.

public static SelectList ToSelectList<T>(T selectedItem)
        {
            if (!typeof(T).IsEnum) throw new InvalidEnumArgumentException("The specified type is not an enum");

            var selectedItemName = Enum.GetName(typeof (T), selectedItem);
            var items = new List<SelectListItem>();
            foreach (var item in Enum.GetValues(typeof(T)))
            {
                var fi = typeof(T).GetField(item.ToString());
                var attribute = fi.GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault();

                var enumName = Enum.GetName(typeof (T), item);
                var title = attribute == null ? enumName : ((DescriptionAttribute)attribute).Description;

                var listItem = new SelectListItem
                {
                    Value = enumName,
                    Text = title,
                    Selected = selectedItemName == enumName
                };
                items.Add(listItem);
            }

            return new SelectList(items, "Value", "Text");
        }

3
    public enum EnumStates
    {
        AL = 0,
        AK = 1,
        AZ = 2,
        WY = 3
    }


@Html.DropDownListFor(model => model.State, (from EnumStates e in Enum.GetValues(typeof(EnumStates))
                                                               select new SelectListItem { Value = ((int)e).ToString(), Text = e.ToString() }), "select", new { @style = "" })
                @Html.ValidationMessageFor(model => model.State)  //With select



//Or


@Html.DropDownListFor(model => model.State, (from EnumStates e in Enum.GetValues(typeof(EnumStates))
                                                               select new SelectListItem { Value = ((int)e).ToString(), Text = e.ToString() }), null, new { @style = "" })
                @Html.ValidationMessageFor(model => model.State)   //With out select

EnumState'i nerede tanımlıyorsunuz?
superartsy

üstte görebilirsiniz ... public enum EnumStates
Thulasiram

2

Mike'ınki ile aynı (uzun yanıtların arasına gömülü)

model.truckimagelocation, TruckImageLocation numaralandırma türünün sınıf örneği özelliğidir

@Html.DropDownListFor(model=>model.truckimagelocation,Enum.GetNames(typeof(TruckImageLocation)).ToArray().Select(f=> new SelectListItem() {Text = f, Value = f, Selected = false}))

2

Bu, tüm Enümler için kullanılacak en genel koddur.

public static class UtilitiesClass
{

    public static SelectList GetEnumType(Type enumType)
    {
        var value = from e in Enum.GetNames(enumType)
                    select new
                    {
                        ID = Convert.ToInt32(Enum.Parse(enumType, e, true)),
                        Name = e
                    };
        return new SelectList(value, "ID", "Name");
    }
}

Eylem Yöntemi

ViewBag.Enum= UtilitiesClass.GetEnumType(typeof (YourEnumType));

View.cshtml

 @Html.DropDownList("Type", (IEnumerable<SelectListItem>)ViewBag.Enum, new { @class = "form-control"})

1

modelinizde numaralandırmayı kullanabilirsiniz

Numaranız

public enum States()
{
  AL,AK,AZ,...WY
}

bir model yapmak

public class enumclass
{
public States statesprop {get; set;}
}

görünümünde

@Html.Dropdownlistfor(a=>a.statesprop)

Son Sorular Cevap kar.
Anup

1

MVC5'teki en kolay cevap Enum Tanımla'dır:

public enum ReorderLevels {
          zero = 0,
            five = 5,
            ten = 10,
            fifteen = 15,
            twenty = 20,
            twenty_five = 25,
            thirty = 30
        }

Görünümde Bağla:

        <div class="form-group">
            <label>Reorder Level</label>
            @Html.EnumDropDownListFor(m => m.ReorderLevel, "Choose Me", new { @class = "form-control" })
        </div>
Sitemizi kullandığınızda şunları okuyup anladığınızı kabul etmiş olursunuz: Çerez Politikası ve Gizlilik Politikası.
Licensed under cc by-sa 3.0 with attribution required.