2

コントローラのパラメータの表示名にアクセスすることはできますか?たとえば、パラメータを次のように定義したとします。

public class Class1
{
  [DisplayName("First Name")]
  public string firstname { get; set; }
}

コントローラの名の表示名にアクセスできるようにしたいと思います。何かのようなもの

string name = Model.Class1.firstName.getDisplayName();

getDisplayName()表示名を取得するために使用できるような方法はありますか?

4

3 に答える 3

4

まず、そのプロパティを表すMemberInfoオブジェクトを取得する必要があります。何らかの形で振り返る必要があります。

MemberInfo property = typeof(Class1).GetProperty("Name");

(私は「古いスタイル」のリフレクションを使用していますが、コンパイル時に型にアクセスできる場合は、式ツリーを使用することもできます)

次に、属性をフェッチして、DisplayNameプロパティの値を取得できます。

var attribute = property.GetCustomAttributes(typeof(DisplayNameAttribute), true)
      .Cast<DisplayNameAttribute>().Single();
string displayName = attribute.DisplayName;
于 2013-01-14T07:58:23.773 に答える
1

このリンクで答えを見つけました。Htmlヘルパークラスを作成し、その名前空間をビューweb.configに追加して、コントローラーで使用しました。リンクにすべて記載されています

于 2013-01-14T13:11:43.153 に答える
0

列挙型の表示名は次のようになります

これが例です

public enum Technology
{
  [Display(Name = "AspNet Technology")]
  AspNet,
  [Display(Name = "Java Technology")]
  Java,
  [Display(Name = "PHP Technology")]
  PHP,
}

とこのような方法

public static string GetDisplayName(this Enum value)
{
var type = value.GetType();

var members = type.GetMember(value.ToString());
if (members.Length == 0) throw new ArgumentException(String.Format("error '{0}' not found in type '{1}'", value, type.Name));

var member = members[0];
var attributes = member.GetCustomAttributes(typeof(DisplayAttribute), false);
if (attributes.Length == 0) throw new ArgumentException(String.Format("'{0}.{1}' doesn't have DisplayAttribute", type.Name, value));

var attribute = (DisplayAttribute)attributes[0];
return attribute.GetName();
}

そしてあなたのコントローラーはこのように

public ActionResult Index()
{
  string DisplayName = Technology.AspNet.GetDisplayName();

  return View();
}

クラスプロパティの場合は、次の手順に従います

public static string GetDisplayName2<TSource, TProperty> (Expression<Func<TSource, TProperty>> expression)
    {
        var attribute =   Attribute.GetCustomAttribute(((MemberExpression)expression.Body).Member, typeof(DisplayAttribute)) as DisplayAttribute;
        return attribute.GetName();
    }

このようにコントローラーでこのメソッドを呼び出します

// Class1 is your classname and firstname is your property of class
string localizedName = Testing.GetDisplayName2<Class1, string>(i => i.firstname);
于 2016-09-05T16:10:59.753 に答える