Framework Madness!

And other adventures C# and asp.net …

Asp.net MVC 2 Tip – Default DateTime value on Action Method Parameter

with one comment

One of the new features in Asp.Net MVC 2 is the support for setting a default value for an action method inside a controller. Here is an example:

   1: public ActionResult Article ([DefaultValue(0)] Int64 id)

All you need to do is apply the ‘DefaultValue’ attribute with a constant value. But, if you have a DateTime value to set as a default there is a small trick. Here is what does not work:

   1: public ActionResult ByMonth ([DefaultValue(DateTime.Today)]DateTime id)

That won’t compile because the DateTime is never a constant value. You can’t even make a constant. But you can do this:

   1: public ActionResult ByMonth (

   2:     [DefaultValue(typeof(DateTime),"2000-01-01")]

   3:     DateTime id)  

This works because the string and type are constants.

Advertisements

Written by Lynn Eriksen

September 13, 2009 at 5:21 am

Posted in Uncategorized

Tagged with

One Response

Subscribe to comments with RSS.

  1. […] to VoteAsp.net MVC 2 Tip – Default DateTime value on Action Method Parameter (9/13/2009)Sunday, September 13, 2009 from leriksen71.wordpress.comOne of the new features in Asp. Net MVC 2 is […]


Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: