6

I am trying to make it so when a user enters a value and submits it, it is stored with the first letter per word capitalized and the rest lower case. I want to do it for model.Name in:

 @Html.EditorFor(model => model.Name)

I found this neat function that does what I want, but I can't for the life of me figure out how to combine the two:

s = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(s.toLower());

I would seriously appreciate any help, I have been working on this forever and nothing to show for it yet.

tereško
  • 58,060
  • 25
  • 98
  • 150
kgst
  • 243
  • 1
  • 2
  • 13
  • CSS only solution - may not work for you if you need code only - http://stackoverflow.com/questions/5577364/make-the-first-character-uppercase-in-css . (There is more info if searching for [css uppercase first letter](http://www.bing.com/search?q=css+uppercase+first+letter) ) – Alexei Levenkov Jul 02 '13 at 00:08
  • I haven't explored mvc much yet. But, I think this can be done with a custom attribute on the model field. – mshsayem Jul 02 '13 at 00:56

3 Answers3

2

Considering that your string is in a variable called "strSource", then you can do something like this:

char.ToUpper(strSource[0]).ToString() + strSource.Substring(1).ToLower();

Or, the better solution would be to create an extension method:

public static string ToUpperFirstLetter(this string strSource)
{
  if (string.IsNullOrEmpty(strSource)) return strSource;
  return char.ToUpper(strSource[0]).ToString() + strSource.Substring(1).ToLower();
}
bazz
  • 613
  • 4
  • 10
0

An option would be to make a custom EditorTemplate (Views -> Shared -> EditorTemplates)

TitleString.ascx

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.String>" %>
<%=Html.TextBox("", System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(Model.ToLower()))%>

And then in your view where you want that formatting you can do something like:

@Html.EditorFor(model => model.Name, "TitleString")

For more details check out: http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-1-introduction.html

ChrisHDog
  • 4,473
  • 8
  • 51
  • 77
0

You can capitalize the first letter of each word according to CultureInfo by simply using this on the Controller:

Note: "test" is a sample property returned from the View (as Name, Surname, Address, etc.)

text = string.IsNullOrEmpty(text) ? string.Empty : CultureInfo.CurrentCulture.TextInfo.ToTitleCase(text.ToLower(new CultureInfo("tr-TR", false)));

Please note that, in here there is an extra control for null values.

Murat Yıldız
  • 11,299
  • 6
  • 63
  • 63