SB2055 SB2055 - 1 year ago 54
C# Question

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

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download