0

My view takes in the entity directly as the model:

@model MyProject.Models.MyEntity

Is there an easy way to get the plural name of the entity within the view? In the above example, I would want MyEntities.

I know I can do this in a helper, or in the controller and pass it into the ViewBag or a ViewModel - but is there a direct way of getting it while in the view instead?

The non-plural name would do, as I've created an extension method on the String object that pluralises a word:

using System.Data.Entity.Design.PluralizationServices;

namespace System
{
    public static class StringExtensionMethods
    {
        public static string Pluralise(this string word, CultureInfo culture)
        {
            var service = PluralizationService.CreateService(culture);

            if (service.IsSingular(word))
            {
                return service.Pluralize(word);
            }

            return word;
    }
}

PS. If anyone wants to use the above then a reference to System.Data.Entity.Design is needed.

EDIT:

I just realised I can do Model.GetType().Name.Pluralise(); because that's what I am passing in.

Ah well... is there a better way?

PeteGO
  • 5,597
  • 3
  • 39
  • 70

1 Answers1

0

That's pretty much the best way to do it, however most would argue you should be doing it in the controller, and passing the pluralized name to the view via a ViewModel

Nick Albrecht
  • 16,607
  • 10
  • 66
  • 101