Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using nameof() to inspect class name with its parent for MVC validation

I'm attempting to add an error to the ModelState by using nameof:

 @Html.ValidationMessageFor(m => m.Foo.Bar)

In the view, this has been tagged with a name of Foo.Bar.

When I add a model state error, I have to key that error to a name, so I use nameof(Foo.Bar) - however this just gives me Bar, when I need Foo.Bar. Right now I can hardcode Foo.Bar but I'd rather use a strongly-typed method. What are my options?

like image 241
SB2055 Avatar asked Nov 16 '16 07:11

SB2055


2 Answers

There is not built-in way to do that, but there are some workarounds.

You can concantenate names of the namespaces yourself (no runtime penalty, but hard to maintain):

String qualifiedName = String.Format("{0}.{1}", nameof(Foo), nameof(Bar));

Another option is to use reflecton to get the fully qualified name directly (easier, but has some runtime penalty):

String qualifiedName = typeof(Foo.Bar).FullName;

Hope this helps.

like image 70
Eduard Malakhov Avatar answered Oct 11 '22 02:10

Eduard Malakhov


A better way is to use expression trees.
You can have your own ValidationMessageFor extension method.
Check my NameOf method in the following example

using System;
using System.Linq;
using System.Linq.Expressions;

namespace Name
{
    class MyClass
    {
        public int MyProperty { get; set; }
        public MyClass Foo { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(new MyClass().NameOf(m => m.MyProperty));//MyProperty
            Console.WriteLine(new MyClass().NameOf(m => m.Foo.MyProperty));//Foo.MyProperty
            Console.ReadLine();
        }
    }

    public static class MyExtentions
    {
        public static string NameOf<T, TProperty>(this T t, Expression<Func<T, TProperty>> expr)
        {
            return string.Join(".", expr.ToString().Split('.').Skip(1));
        }
    }
}
like image 45
George Vovos Avatar answered Oct 11 '22 03:10

George Vovos