0

Trying to force text in certain fields in a view that is adding records to the DB via Entity framework to uppercase.

Can I do it in the view EditorFor or can I do it in the controller to all fields easily before firing db.SaveChanges()?

Doug Farrell
  • 135
  • 1
  • 3
  • 20

2 Answers2

1

You could loop through the properties on your ViewModel server side using a helper method.

public T ViewModelToUpper<T>(T viewModel) where T : class
{
    foreach (var property in viewModel.GetType().GetProperties())
    {
        var value = property.GetValue(viewModel, null);
        if (value is string)
        {
            property.SetValue(viewModel, value.ToString().ToUpper());
        }
    }

    return viewModel;
}

Then you can call viewModel = ClassName.ViewModelToUpper(viewModel). Now you don't have to worry about doing it for every string property as this will happen anyway.

ediblecode
  • 11,701
  • 19
  • 68
  • 116
0

You can do this in the UI with jQuery if you'd like. It's a little weird from a user perspective to be typing and have everything converted to uppercases (I'd check my caps lock). Convert to uppercase as user types using javascript

Your other option, better IMO, is to do this in the controller. You can use ToUpper()on the strings. Keep Globalization in mind.

Community
  • 1
  • 1
Josh
  • 1,724
  • 13
  • 15
  • The user is irrelevant at this point, it is being done in the db to adhear to a specific export format. – Doug Farrell Feb 09 '15 at 17:31
  • Can I do that to all string fields when I do db.Travelers.Add(traveler); db.SaveChanges(); or would I have to do each string field separately ? – – Doug Farrell Feb 09 '15 at 17:31
  • Well, you could do a partial class for the DB entity and put a method on it to do all the strings at once. Think: 'Travelers.Upper()' that goes through and does everything. Otherwise you'll do them individually. – Josh Feb 09 '15 at 17:47