Defining a method in a view

I know there will be much gnashing of teeth from MVC purists for even thinking about designing a view this way, but if you need to define a method inside a view, you can do it like I show below. In this instance, I am writing a method that will take a date, determine if it is null, and return either the short date or an empty string:

First, the method, defined at the top of the view:

 var getDate = new Func<DateTime, string>((date) => date != DateTime.MinValue ? date.ToShortDateString() : String.Empty);

And then calling the method:

@foreach (Models.Coaster item in Model.Coasters) {
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: