Using nameof () to validate a class name with its parent name for MVC validation

I am trying to add an error to ModelState using nameof:

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

In the view, this is tagged with name Foo.Bar .

When I add a model state error, I have to point this error to name , so I use nameof(Foo.Bar) , but it just gives me Bar when I need Foo.Bar . I can make hardcode Foo.Bar right now, but I would prefer to use a strongly typed method. What are my options?

+5
source share
2 answers

There is no built-in way to do this, but there are some workarounds.

You can directly specify namespace names (no runtime, but hard to maintain):

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

Another option is to use a reflecton to get the full name directly (simpler, but has some runtime):

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

Hope this helps.

+4
source

It is best to use expression trees.
You may have your own ValidationMessageFor extension method.
Check out 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)); } } } 
+1
source

Source: https://habr.com/ru/post/1259809/


All Articles