Mark Gilbert's Blog

Science and technology, served light and fluffy.

It’s a Long shot – ASP.NET Routing and Enumeration Values

Now that the actual development frenzy has started to subside for my latest MVC project, I can start working on the backlog of technical posts related to various issues we encountered.  Today’s involves ASP.NET Routing.  I wanted to establish multiple versions of a gallery page, each filtered to a specific occasion (weddings, birthdays, etc.).  The URLs would look like these:

Gallery.aspx/just-because

Gallery.aspx/weddings

Gallery.aspx/birthdays

I had already set up an enumeration that held the values I wanted to use.  Behind the scenes, the numeric values for these items corresponded to IDs in the database:

Public Enum Specials As Long
    JustBecause = 1
    Weddings = 2
    Birthdays = 3
End Enum

I then proceeded to established my routes in my Global.asax/Application_Start handler (just the first rule is shown):

routes.MapRoute( _
    "Gallery-JustBecause", _
    "Gallery.aspx/just-because", _
    New With {.controller = "Gallery", .action = "ByOccasion", .id = Occasion.Specials.JustBecause} _
)

When I tried to fire up the site, however, I got this error:

The parameters dictionary contains a null entry for parameter ‘id’ of non-nullable type ‘System.Int64’ for method ‘System.Web.Mvc.ActionResult Index(Int64)’ in ‘MyProject.GalleryController’. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.

Parameter name: parameters

I tried replacing “Occasion.Specials.JustBecause” with the number “1”, and it worked fine.  For whatever reason, even though my enumeration was of type Long under the hood, Routing was not buying it.  However, manually casting the original enumeration value to a Long did the trick:

routes.MapRoute( _
    "Gallery-JustBecause", _ 
"Gallery.aspx/just-because", _
New With {.controller = "Gallery", .action = "ByOccasion", .id = CType(Occasion.Specials.JustBecause, Long)} _ )

And there was much rejoicing.

Advertisements

June 27, 2011 - Posted by | ASP.NET MVC

Sorry, the comment form is closed at this time.

%d bloggers like this: