mvc display name alternative

public class Principal
    {
        [DisplayName("PrincipalFirstName")]        
        public string firstName { get; set; }
      }

public static class Generic
    {
            public static string GetDisplayName<TModel, TProperty>(this TModel model, Expression<Func<TModel, TProperty>> expression)
            {
                return ModelMetadata.FromLambdaExpression<TModel, TProperty>(
                    expression,
                    new ViewDataDictionary<TModel>(model)
                    ).DisplayName;
            }
       
    }


client call:

 Domain.Principal principal = new Domain.Principal();
 string principalFirstName = Utility.Generic.GetDisplayName(principal, m => m.firstName);
 Response.Write(principalFirstName)

Above codes are working. I can get end result "PrincipalFirstName"
However I want to use something else instead of DisplayName like below.

           
public class Principal
    {
        [XmlName("PrincipalFirstName")]        
        public string firstName { get; set; }
      }

is it possible?
LVL 1
ITsolutionWizardAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

it_saigeDeveloperCommented:
Sure you could, you would just use reflection.  Give me a few I'll whip up an example.

-saige-
ITsolutionWizardAuthor Commented:
it_saigeDeveloperCommented:
Does this fit the bill for you?
using System;
using System.Linq.Expressions;

namespace EE_Q28701278
{
	class Program
	{
		static void Main(string[] args)
		{
			Parent mom = new Parent() { ID = 1, Name = "Mom1" };
			Child daughter = new Child() { ID = 1, Name = "Daughter1" };

			Console.WriteLine("Mom's ID is {0}", mom.GetAttributedValue<Parent, TeacherAttribute>(m => m.ID, "-1"));
			Console.WriteLine("Daughter's Name is {0}", daughter.GetAttributedValue<Child, StudentAttribute>(m => m.Name, "No Name"));
			Console.ReadLine();
		}
	}

	class Parent
	{
		[Teacher("TeacherID")]
		public int ID { get; set; }
		[Teacher("TecherName")]
		public string Name { get; set; }
	}

	class Child
	{
		[Student("StudentID")]
		public int ID { get; set; }
		[Student("StudentName")]
		public string Name { get; set; }
	}

	class TeacherAttribute : Attribute
	{
		public string Name { get; set; }

		public TeacherAttribute() { ;}

		public TeacherAttribute(string Name) { this.Name = Name; }
	}

	class StudentAttribute : Attribute
	{
		public string Name { get; set; }

		public StudentAttribute() { ;}

		public StudentAttribute(string Name) { this.Name = Name; }
	}

	static class Extensions
	{
		public static string GetAttributedValue<T, A>(this T instance, Expression<Func<T, object>> expression, string defaultValue = default(string))
		{
			if (expression == null)
				throw new ArgumentException("The expression cannot be null.", "expression");

			string name = string.Empty;
			try { name = expression.Body.GetMemberName(); }
			catch (Exception) { throw new ArgumentException("The membername could not be resolved from the expression.", "expression"); }

			foreach (var prop in instance.GetType().GetProperties())
			{
				if (prop.Name.Equals(name))
				{
					object o = null;
					A[] attributes = prop.GetCustomAttributes(typeof(A), false) as A[];
					foreach (A attribute in attributes)
						o = prop.GetValue(instance, null);

					if (o != null)
						return o.ToString();
				}
			}
			return defaultValue ?? string.Empty;
		}

		static string GetMemberName(this Expression expression)
		{
			if (expression == null)
				throw new ArgumentException("The expression cannot be null.");

			// Reference type property of field
			if (expression is MemberExpression)
				return ((MemberExpression)expression).Member.Name;

			// Reference type method
			if (expression is MethodCallExpression)
				return ((MethodCallExpression)expression).Method.Name;

			if (expression is LambdaExpression)
				return ((MethodCallExpression)((LambdaExpression)expression).Body).Method.Name;

			// Property, field or method returning value type
			if (expression is UnaryExpression)
				return ((UnaryExpression)expression).GetMemberName();

			throw new ArgumentException("Invalid expression.", "expression");
		}

		/// <summary>Gets the name of the member.</summary>
		/// <param name="expression">The expression.</param>
		/// <returns>System.String.</returns>
		static string GetMemberName(this UnaryExpression expression)
		{
			if (expression.Operand is MethodCallExpression)
				return ((MethodCallExpression)expression.Operand).Method.Name;

			return ((MemberExpression)expression.Operand).Member.Name;
		}
	}
}

Open in new window

Produces the following output - Capture.JPGOfcourse if you want the property name as defined by the attribute, this could be modified as such:
using System;
using System.Linq.Expressions;
using System.Collections.Generic;

namespace EE_Q28701278
{
	class Program
	{
		static void Main(string[] args)
		{
			Parent mom = new Parent() { ID = 1, Name = "Mom1" };
			Child daughter = new Child() { ID = 1, Name = "Daughter1" };

			Console.WriteLine("{0} is {1}", mom.GetAttributedValue<Parent, TeacherAttribute>(m => m.ID, "-1").Key.Name, mom.GetAttributedValue<Parent, TeacherAttribute>(m => m.ID, "-1").Value);
			Console.WriteLine("{0} is {1}", daughter.GetAttributedValue<Child, StudentAttribute>(m => m.Name, "No Name").Key.Name, daughter.GetAttributedValue<Child, StudentAttribute>(m => m.Name, "No Name").Value);
			Console.ReadLine();
		}
	}

	class Parent
	{
		[Teacher("TeacherID")]
		public int ID { get; set; }
		[Teacher("TecherName")]
		public string Name { get; set; }
	}

	class Child
	{
		[Student("StudentID")]
		public int ID { get; set; }
		[Student("StudentName")]
		public string Name { get; set; }
	}

	class TeacherAttribute : Attribute
	{
		public string Name { get; set; }

		public TeacherAttribute() { ;}

		public TeacherAttribute(string Name) { this.Name = Name; }
	}

	class StudentAttribute : Attribute
	{
		public string Name { get; set; }

		public StudentAttribute() { ;}

		public StudentAttribute(string Name) { this.Name = Name; }
	}

	static class Extensions
	{
		public static KeyValuePair<A, string> GetAttributedValue<T, A>(this T instance, Expression<Func<T, object>> expression, string defaultValue = default(string))
		{
			if (expression == null)
				throw new ArgumentException("The expression cannot be null.", "expression");

			string name = default(string);

			try { name = expression.Body.GetMemberName(); }
			catch (Exception) { throw new ArgumentException("The membername could not be resolved from the expression.", "expression"); }

			foreach (var prop in instance.GetType().GetProperties())
			{
				if (prop.Name.Equals(name))
				{
					object o = null;
					A[] attributes = prop.GetCustomAttributes(typeof(A), false) as A[];
					if (attributes.Length >= 1)
					{
						try { return new KeyValuePair<A, string>(attributes[0], prop.GetValue(instance, null).ToString()); }
						catch (Exception) { ;}
					}
				}
			}
			return new KeyValuePair<A, string>(default(A), defaultValue ?? string.Empty);
		}

		//public static string GetAttributedValue<T, A>(this T instance, Expression<Func<T, object>> expression, string defaultValue = default(string))
		//{
		//     if (expression == null)
		//          throw new ArgumentException("The expression cannot be null.", "expression");

		//     string name = string.Empty;
		//     try { name = expression.Body.GetMemberName(); }
		//     catch (Exception) { throw new ArgumentException("The membername could not be resolved from the expression.", "expression"); }

		//     foreach (var prop in instance.GetType().GetProperties())
		//     {
		//          if (prop.Name.Equals(name))
		//          {
		//               object o = null;
		//               A[] attributes = prop.GetCustomAttributes(typeof(A), false) as A[];
		//               foreach (A attribute in attributes)
		//                    o = prop.GetValue(instance, null);

		//               if (o != null)
		//                    return o.ToString();
		//          }
		//     }
		//     return defaultValue ?? string.Empty;
		//}

		static string GetMemberName(this Expression expression)
		{
			if (expression == null)
				throw new ArgumentException("The expression cannot be null.");

			// Reference type property of field
			if (expression is MemberExpression)
				return ((MemberExpression)expression).Member.Name;

			// Reference type method
			if (expression is MethodCallExpression)
				return ((MethodCallExpression)expression).Method.Name;

			if (expression is LambdaExpression)
				return ((MethodCallExpression)((LambdaExpression)expression).Body).Method.Name;

			// Property, field or method returning value type
			if (expression is UnaryExpression)
				return ((UnaryExpression)expression).GetMemberName();

			throw new ArgumentException("Invalid expression.", "expression");
		}

		/// <summary>Gets the name of the member.</summary>
		/// <param name="expression">The expression.</param>
		/// <returns>System.String.</returns>
		static string GetMemberName(this UnaryExpression expression)
		{
			if (expression.Operand is MethodCallExpression)
				return ((MethodCallExpression)expression.Operand).Method.Name;

			return ((MemberExpression)expression.Operand).Member.Name;
		}
	}
}

Open in new window

Which now produces the following output -Capture.JPG-saige-
C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

ITsolutionWizardAuthor Commented:
I do not understand what it is.
it_saigeDeveloperCommented:
What do you not understand?  Or perhaps I misunderstood your requirements.

-saige-
ITsolutionWizardAuthor Commented:
public class Principal
    {
        [DisplayName("PrincipalFirstName")]        
        public string firstName { get; set; }
      }

I have above but I want to customize like below

public class Principal
    {
        [XmlDisplayName("PrincipalFirstName")]        
        public string firstName { get; set; }
      }

and on .cs I want to capture the value of xmldisplayname and result will be principalfirstname
it_saigeDeveloperCommented:
So then does this meet your requirements?
using System;
using System.Linq.Expressions;
using System.Collections.Generic;

namespace EE_Q28701278
{
	class Program
	{
		static void Main(string[] args)
		{
			Principal pr = new Principal() { FirstName = "John" };

			Console.WriteLine("{0} is {1}", pr.GetAttributedValue<Principal, XmlDisplayNameAttribute>(m => m.FirstName, "No Name").Key.Name, pr.GetAttributedValue<Principal, XmlDisplayNameAttribute>(m => m.FirstName, "No Name").Value);
			Console.ReadLine();
		}
	}

	class Principal
	{
		[XmlDisplayName("PrincipalFirstName")]
		public string FirstName { get; set; }
	}

	class XmlDisplayNameAttribute : Attribute
	{
		public string Name { get; set; }

		public XmlDisplayNameAttribute() { ;}

		public XmlDisplayNameAttribute(string Name) { this.Name = Name; }
	}

	static class Extensions
	{
		public static KeyValuePair<A, string> GetAttributedValue<T, A>(this T instance, Expression<Func<T, object>> expression, string defaultValue = default(string)) where A : Attribute
		{
			if (expression == null)
				throw new ArgumentException("The expression cannot be null.", "expression");

			string name = default(string);

			try { name = expression.Body.GetMemberName(); }
			catch (Exception) { throw new ArgumentException("The membername could not be resolved from the expression.", "expression"); }

			foreach (var prop in instance.GetType().GetProperties())
			{
				if (prop.Name.Equals(name))
				{
					object o = null;
					A[] attributes = prop.GetCustomAttributes(typeof(A), false) as A[];
					if (attributes.Length >= 1)
					{
						try { return new KeyValuePair<A, string>(attributes[0], prop.GetValue(instance, null).ToString()); }
						catch (Exception) { ;}
					}
				}
			}
			return new KeyValuePair<A, string>(default(A), defaultValue ?? string.Empty);
		}

		static string GetMemberName(this Expression expression)
		{
			if (expression == null)
				throw new ArgumentException("The expression cannot be null.");

			// Reference type property of field
			if (expression is MemberExpression)
				return ((MemberExpression)expression).Member.Name;

			// Reference type method
			if (expression is MethodCallExpression)
				return ((MethodCallExpression)expression).Method.Name;

			if (expression is LambdaExpression)
				return ((MethodCallExpression)((LambdaExpression)expression).Body).Method.Name;

			// Property, field or method returning value type
			if (expression is UnaryExpression)
				return ((UnaryExpression)expression).GetMemberName();

			throw new ArgumentException("Invalid expression.", "expression");
		}

		/// <summary>Gets the name of the member.</summary>
		/// <param name="expression">The expression.</param>
		/// <returns>System.String.</returns>
		static string GetMemberName(this UnaryExpression expression)
		{
			if (expression.Operand is MethodCallExpression)
				return ((MethodCallExpression)expression.Operand).Method.Name;

			return ((MemberExpression)expression.Operand).Member.Name;
		}
	}
}

Open in new window

Which produces the following output -Capture.JPG-saige-
ITsolutionWizardAuthor Commented:
not working below code is in red

name = expression.Body.GetMemberName();
it_saigeDeveloperCommented:
What is the error you are receiving?

-saige-

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
ITsolutionWizardAuthor Commented:
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.