8

I am new to MVC and have not found a solution for this online.

I have the html as :

@Html.DisplayFor(model => model.Address1) <br />

I want all the first letter of address1 to be capital letters e.g. Something Road instead of something road.

Now I have a class client and property Address1 and using EF to get the address as follow:

 public class MyDBContext : DbContext
    {
        public DbSet<Client> Clients { get; set; }
    }

Hope it makes sense.

tereško
  • 58,060
  • 25
  • 98
  • 150
Zaki
  • 5,540
  • 7
  • 54
  • 91

9 Answers9

21

easy solution could be

Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { class = "form-control" } })

then use below css to capitalize your first letter then you done.

.form-control {
text-transform:capitalize;
}
kiflay
  • 699
  • 2
  • 7
  • 14
6

You could add a partial class for Client with a property that returns Address1 in title case:

public partial class Client
{
    public string TitleCaseAddress1
    {
        get
        {
            return System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(this.Address1);
        }
    }
}

You would then use TitleCaseAddress1 in your Razor:

@Html.DisplayFor(model => model.TitleCaseAddress1) <br />

Reference: http://msdn.microsoft.com/en-us/library/system.globalization.textinfo.totitlecase(v=vs.100).aspx

Gromer
  • 9,861
  • 4
  • 34
  • 55
5

For anyone looking to do this strictly in Razor, this example is converting the logged-in user name. Replace with your string variable.

This gets first letter and converts to upper:

@(@User.Identity.GetUserName().ToString().Substring(0, 1).ToUpper())

This gets the remaining string.

@(@User.Identity.GetUserName().ToString().Substring(1, 
    User.Identity.GetUserName().ToString().Length - 1))

Just put them together like so to get the whole string.

@(@User.Identity.GetUserName().ToString().Substring(0, 
    1).ToUpper())@(@User.Identity.GetUserName().ToString().Substring(1, 
    User.Identity.GetUserName().ToString().Length - 1))
MarredCheese
  • 17,541
  • 8
  • 92
  • 91
TomS
  • 51
  • 1
  • 1
4

It's best to keep the presentation layer and the data access layer separate. Create a view model that wraps or translates the ORM / entity framework objects.

public class ClientViewModel
{
    private Client _dao;

    public ClientViewModel(Client dao)
    {
        _dao = dao;
    }

    public string Address 
    { 
        get
        {
            // modify the address as needed here
            return _dao.Address;
        }
    }
}
McGarnagle
  • 101,349
  • 31
  • 229
  • 260
  • if I do it this way would that mean I can validate all my properties...say one of my property is empty string and in html output dont want to show it would this be possible? – Zaki Oct 03 '12 at 16:49
  • @Sam1 I saw your other question -- that's really an issue with the view, but yes, you should be able to do that. – McGarnagle Oct 03 '12 at 16:51
  • Hi, have done it this way so how do I call Address in my view now? – Zaki Oct 04 '12 at 07:54
  • @Sam1 Same way, `@Html.DisplayFrom(model => model.Address)`. Use Robuust's answer to format the string. – McGarnagle Oct 04 '12 at 16:12
3

Here is the correct way to accomplish what you want, I've implemented it for you.

There is an HtmlStringFormatter.Create() which allow you to pass a delegate and make your own anonymous formatter.

Code Sample:

// This just upper case all the letters.
@Html.DisplayFormatFor(model => model.Address, HtmlStringFormatter.Create(s=> s.ToUpper()))

If You to create a custom formatter, derive from HtmlStringFormatter and set its delegate property to whatever manipulation you want to do.

Code Sample:

// Here I use the Capital Letter custom formatter.
@Html.DisplayFormatFor(model => model.Address, new CapitalLetterFormatter())

All the classes:

namespace MvcPlay.HelperExtensions
{
    public static class HelperExtensions
    {
        public static MvcHtmlString DisplayFormatFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, HtmlStringFormatter formatter)
        {
            var output = helper.DisplayFor(expression);
            string formatted = formatter.Delegate.Invoke(output.ToString());
            return MvcHtmlString.Create(formatted);
        }
    }
}

namespace MvcPlay.HtmlStringFormatting
{
    public class HtmlStringFormatter
    {
        public delegate string FormatDelegate(string s);

        public FormatDelegate Delegate;
        public Expression<FormatDelegate> formatExpression;

        private HtmlStringFormatter(FormatDelegate expression)
        {
            Delegate = expression;
        }

        protected HtmlStringFormatter()
        {

        }

        public static HtmlStringFormatter Create(FormatDelegate expression)
        {
            return new HtmlStringFormatter(expression);
        }
    }

    public class CapitalLetterFormatter : HtmlStringFormatter
    {
        public CapitalLetterFormatter()
        {
            Delegate =
                s => new CultureInfo("en-US", false).TextInfo.ToTitleCase(s).ToString(CultureInfo.InvariantCulture);

        }
    }
}

Don't forget to add the following lines to the Web.Config at the Views folder:

<add namespace="MvcPlay.HelperExtensions" />
<add namespace="MvcPlay.HtmlStringFormatting"/>

This will include the Formatters and the Helper Extension automatically so you won't need to include it inside every view that you want to use it in.

Aviran Cohen
  • 5,581
  • 4
  • 48
  • 75
  • no comment? anyway, Have a look on my solution - it is way more reusable and doesn't require to create ViewModels each time you want to show a data in a different way. – Aviran Cohen Oct 08 '12 at 00:02
2

You can just use C# code for this: example from: http://www.dotnetperls.com/uppercase-first-letter

using System;

class Program
{
    static void Main()
    {
    Console.WriteLine(UppercaseFirst("samuel"));
    Console.WriteLine(UppercaseFirst("julia"));
    Console.WriteLine(UppercaseFirst("john smith"));
    }

    static string UppercaseFirst(string s)
    {
    // Check for empty string.
    if (string.IsNullOrEmpty(s))
    {
        return string.Empty;
    }
    // Return char and concat substring.
    return char.ToUpper(s[0]) + s.Substring(1);
    }
}
Rob
  • 3,556
  • 2
  • 34
  • 53
  • and how would I do it using MVC? – Zaki Oct 03 '12 at 16:38
  • in MVC you can add c# code blocks. Do you know the basics already of MVC projects or .NET aspx? - I don't have VS2010 available here so I cannot create your code right away. I can tomorrow, if nobody did it before me. Or if you didn't find the solution yourself by then. – Rob Oct 03 '12 at 16:39
  • I can wait till tomorrow as I said am new to mvc bt have experience with asp.net – Zaki Oct 03 '12 at 16:41
  • Works well in Razor: `@char.ToUpper(s[0])s.Substring(1)` – Luke Apr 29 '13 at 14:29
1

Just simply use as follows

@System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(sampleText)
Shanaka Rathnayaka
  • 2,462
  • 1
  • 23
  • 23
0

I know that the original question referred to capitalizing every word in the whole string. But, I got here trying to find a solution to capitalizing the first letter of a string. I agreed with kiflay's answer as the best solution to the OP. But, expanded on it to modify only the first letter, in my usage.

CSS:

blockquote::first-letter {
text-transform: capitalize;}
Khaneliman
  • 334
  • 3
  • 13
0

Using Bootstrap 4.x with Razor you use CSS to capitalize the first letter:

<p class="text-capitalize">CapiTaliZed text.</p>
Robert Stevens
  • 519
  • 5
  • 9