How do you convert input value to title case in EditorFor? I know doing
@Html.EditorFor(model, new { htmlAttributes = new { @style = "text-transform:uppercase" } })
will only change the client side so I need to change it manually on server side.
I tried adding the class text-capitalize
but seems no luck.
Thanks in advance.
Here are explanations to use either title case or sentence case for viewmodel's string properties which bound to EditorFor
:
1) If you want to use title case, you can set it inside getter part with ToTitleCase
method (change CurrentCulture
to InvariantCulture
depending on your requirements), as in example below:
private string _titleCase;
private System.Globalization.CultureInfo culture = System.Threading.Thread.CurrentThread.CurrentCulture;
public string TitleCaseProperty
{
get
{
if (string.IsNullOrEmpty(_titleCase))
{
return _value;
}
else
{
return culture.TextInfo.ToTitleCase(_titleCase.ToLower());
}
}
set
{
_titleCase = value;
}
}
View usage
@Html.EditorFor(model => model.TitleCaseProperty, ...)
2) If you want sentence case instead, use regular expression to find out sequences (referenced from this similar issue) and do similar way to getter part like above:
private string _sentenceCase;
private Regex rgx = new Regex(@"(^[a-z])|[?!.:,;]\s+(.)", RegexOptions.ExplicitCapture);
public string SentenceCaseProperty
{
get
{
if (string.IsNullOrEmpty(_sentenceCase))
{
return _value;
}
else
{
return rgx.Replace(_sentenceCase.ToLower(), s => s.Value.ToUpper());
}
}
set
{
_sentenceCase = value;
}
}
View usage
@Html.EditorFor(model => model.SentenceCaseProperty, ...)
Live example: .NET Fiddle Demo