2013-03-13 3 views
0

템플릿 편집기를 만드는 중입니다. 얻을 modelMetadata와열거 형 속성을 얻는 방법

@model dynamic 


@{ 
    var modelMetadata = Html.GetModelMetadataFor(model => model); 
    var selectList = ReflectionHelpers.GetSelectListByEnumFor(modelMetadata); 
    String name = //get property name; 
} 

모든 권리

하지만 이해할 수없는 속성을 얻을 방법에 대해 설명합니다.

이 코드 사용하기 전에 :

하지만이 시간에 내가 TEnum을 이해가 안 돼요을

내 질문은 :

+0

귀하의 질문이 명확하지 않습니다. 모델의 예를 제공하고이 템플릿을 어떻게 사용하려고합니까? –

+0

이것은 enum의 UIHint입니다. – Mediator

답변

1

에게 당신을 "어떻게 열거 형에서 선택 목록을 생성" 현재 모델의 드롭 다운 목록을 생성하는 사용자 정의 html 도우미를 작성할 수 있습니다 (이 모델은 물론 enum 임).

public static class HtmlExtensions 
{ 
    public static IHtmlString DropDownListForEnum(this HtmlHelper htmlHelper) 
    { 
     var model = htmlHelper.ViewData.Model; 
     if (model == null) 
     { 
      throw new ArgumentException("You must have a model in order to use this method"); 
     } 
     var enumType = model.GetType(); 
     if (!enumType.IsEnum) 
     { 
      throw new ArgumentException("This method works only with enum types."); 
     } 

     var fields = enumType.GetFields(
      BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public 
     ); 
     var values = Enum.GetValues(enumType).OfType<object>(); 
     var items = 
      from value in values 
      from field in fields 
      let descriptionAttribute = field 
       .GetCustomAttributes(
        typeof(DescriptionAttribute), true 
       ) 
       .OfType<DescriptionAttribute>() 
       .FirstOrDefault() 
      let description = (descriptionAttribute != null) 
       ? descriptionAttribute.Description 
       : value.ToString() 
      where value.ToString() == field.Name 
      select new { Id = value, Name = description }; 

     var selectList = new SelectList(items, "Id", "Name", model); 
     return htmlHelper.DropDownList("", selectList); 
    } 
} 
,

다음 템플릿에 단순히이 도우미를 호출

@Html.DropDownListForEnum() 
UPDATE

:

@using System.ComponentModel 
@using System.Reflection 
@using System.Linq; 
@model object 

@{ 
    var model = Html.ViewData.Model; 
    if (model == null) 
    { 
     throw new ArgumentException("You must have a model in order to use this template"); 
    } 
    var enumType = model.GetType(); 
    if (!enumType.IsEnum) 
    { 
     throw new ArgumentException("This method works only with enum types."); 
    } 

    var fields = enumType.GetFields(
     BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public 
    ); 
    var values = Enum.GetValues(enumType).OfType<object>(); 
    var items = 
     from value in values 
     from field in fields 
     let descriptionAttribute = field 
      .GetCustomAttributes(
       typeof(DescriptionAttribute), true 
      ) 
      .OfType<DescriptionAttribute>() 
      .FirstOrDefault() 
     let description = (descriptionAttribute != null) 
      ? descriptionAttribute.Description 
      : value.ToString() 
     where value.ToString() == field.Name 
     select new { Id = value, Name = description }; 

    var selectList = new SelectList(items, "Id", "Name", model); 
} 

@Html.DropDownList("", selectList) 
:

그리고 당신도 그렇게 할 수있는 템플릿에있는 모든 코드를 원한다면

+0

예, 나도 할 수 있습니다. 하지만 나는 따로 따로 구해야한다. 선택 목록, 특성 이름 및 작성 드롭 다운 목록. – Mediator

+0

템플릿의 모든 것을 원하십니까? –

0

불행히도 asp.net 작동 방식을 모르지만 .Net 프레임 워크 내에서이 확장 메서드를 사용합니다.

윈폼 내 6,

public static IList<KeyValuePair<T, string>> ToList<T>() where T : struct 
{ 
    var type = typeof(T); 

    if (!type.IsEnum) 
    { 
     throw new ArgumentException("T must be an enum"); 
    } 

    return (IList<KeyValuePair<T, string>>) 
      Enum.GetValues(type) 
       .OfType<T>() 
       .Select(e => 
       { 
        var asEnum = (Enum)Convert.ChangeType(e, typeof(Enum)); 
        return new KeyValuePair<T, string>(e, GetEnumDescription(asEnum)); 
       }) 
       .ToArray(); 
} 
나는 단순히 호출하여 콤보 상자를 사용할 수 있습니다
var pairs = EnumExtension.ToList<ContenAlignment>(); 
comboBoxFormat.DataSource = pairs; 
comboBoxFormat.ValueMember = "Key"; 
comboBoxFormat.DisplayMember = "Value"; 

은 어쩌면 당신은 asp.net에서 여러분의 필요에 위의 콤보 상자의 코드를 변경할 수 있습니다.