kgst
kgst

Reputation: 243

Capitalizing the first letter of an EditorFor entry

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.

Upvotes: 6

Views: 886

Answers (3)

Murat Yıldız
Murat Yıldız

Reputation: 12032

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.

Upvotes: 0

bazz
bazz

Reputation: 613

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();
}

Upvotes: 2

ChrisHDog
ChrisHDog

Reputation: 4663

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

Upvotes: 0

Related Questions