2

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.

Mace Munch
  • 65
  • 3
  • 10

3 Answers3

1

I would recommend performing this conversion at the getter of this property using .ToUpper()

get {
  if (string.IsNullOrEmpty(_value))
     {
       return _value;
     }
   return _value.ToUpper();
 }
Tushar Gupta
  • 15,504
  • 1
  • 29
  • 47
1

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

Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61
0

easier method

@Html.TextBoxFor(model.FieldName, new { @class = "uppercase" })

css:

.uppercase { text-transform:uppercase }
Bayram Akbuz
  • 75
  • 1
  • 7