简体   繁体   中英

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?

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));
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM