Search code examples
c#asp.net-mvcunobtrusive-validation

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?


Solution

  • 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.