How to pluralize words / lines?

purpose

I want to pluralize words using Razor Engine C # .Net. I am using MVC 4.

Problem

I have the following:

<button class="button light-blue filled compare float-right" title="This product is available in @Model["NumberOfMarketsThatHaveThisProduct"] market(s)"> Compare </button> 

I do not want to use "market (s)", but yes "market" or "markets".

What have i tried

 <button class="button light-blue filled compare float-right" title="This product is available in @Model["NumberOfMarketsThatHaveThisProduct"] @if((int)@Model["NumberOfMarketsThatHaveThisProduct"] == 1) { @: market } else { @: markets }"> Compare </button> 

But I do not feel comfortable.

What should I do?

+7
source share
4 answers

You can use the logic:

 market@ (someNumber == 1 ? "" : "s") 
+6
source

A much better approach is to create a custom HTML helper that will correctly perform pluralization using the .NET 4 PluralizationService (in System.Data.Entity.Design.PluralizationServices namespace is a reference to the System.Data.Entity.Design assembly), which is also used by EF6 to pluralize table names.

The Razor helper is as follows:

 namespace CustomHelpers { public static class CustomHelpers { public static MvcHtmlString Pluralize(this HtmlHelper htmlHelper, string source) { var serv = PluralizationService.CreateService(new System.Globalization.CultureInfo("en-us")); var plural = serv.Pluralize(source); return MvcHtmlString.Create(plural); } } } 

You can easily use this helper in Razor with the following syntax:

 @using CustomHelpers <div class="jumbotron"> <h1>Hi @Html.Pluralize("person")</h1> </div> 

As you can imagine, he correctly pluralizes the Personality to People , Market to Markets and many other words, since it uses the dictionary of plurality. This is much better than using any custom pluralization code.

+4
source

The most “ASP.NET-MVC-esque way” is to use a display template:

 @model int @if (Model == 1) { @String.Format("{0} market", Model) } else { @String.Format("{0} markets", Model) } 

Put this in your DisplayTemplates folder and name it "Market.cshtml". Then in your model do:

 [UIHint("Market")] public int NumberOfMarketsThatHaveThisProduct { get; set; } 

And in your opinion:

 @Html.DisplayFor(m => m.NumberOfMarketsThatHaveThisProduct) 

This approach can be very easily translated by changing the display template to use local resources when and when you need it.

This will be more neat than making it embedded in the view if you need to repeat this a lot. If it is disposable, you may find that it is too much.

+2
source
 @ { string last = Model["NumberOfMarketsThatHaveThisProduct"]==1? "": "'s"; } <button class="button light-blue filled compare float-right" title="This product is available in @Model["NumberOfMarketsThatHaveThisProduct"] market@last "> Compare </button> 
0
source

All Articles