I want to pluralize words with Razor Engine of C#.Net. I'm using MVC 4.
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".
<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 doing it.
What I have to do?
You can use logic:
market@(someNumber == 1 ? "" : "s")
A much better approach is to create a custom HTML Helper that will do the pluralization correctly using .NET 4's PluralizationService (in System.Data.Entity.Design.PluralizationServices
namespace - reference the System.Data.Entity.Design
assembly) which is also used by EF6 to pluralize table names.
The Razor helper looks like this:
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 it will correctly pluralize Person to People, Market to Markets and many other words, since it uses a pluralization dictionary inside. That's much better than using some custom pluralization code.
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 call it "Market.cshtml." Then, in your model, do:
[UIHint("Market")]
public int NumberOfMarketsThatHaveThisProduct { get; set; }
And in your view:
@Html.DisplayFor(m => m.NumberOfMarketsThatHaveThisProduct)
This approach can be very easily translated by modifying your display template to use local resources as and when you need it to.
This will be neater than doing it inline in the view if you have to repeat this a lot. If it's a one-off, you might find it overkill.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With