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?
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.
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));
        }
    }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With