asp.netasp.net-mvc-2c#-4.0

Pass collection of enums to ASP.NET MVC ActionMethod


Is there a way to pass a collection of Enums to an ActionMethod (on a GET) automatically?

For example, if I have the following enum definition:

enum DaysEnum {Sat, Sun, Mon, Tue, Wed, Thu, Fri};

and, I have an ActionMethod definition of:

ActionResult SampleActionMethod ( List<DaysEnum> days)

Is there a way I could render, in a View, a URL that would pass in a collection of DayEnums. Something like:

var someDays = new List<DaysEnum> {DaysEnum.Sat, DaysEnum.Sun, DaysEnum.Mon};

Url.Route(new { days = someDays, controller="whatever", action="SampleActionMethod"});

The default model binder doesn't seem to support this, since I'm currently getting the following rendered:

http://.../System.Collections.Generic.List`1[DaysEnum]

I know I can do this by manually flattening the collection to, say, a dash-deliniated string, and then recreate the collection in the ActionMethod, but I was looking at something more elegant. Various blog posts talk about passing in collections, but that is more about when doing POSTS.


Solution

  • <%= Html.ActionLink("test enums", "SampleActionMethod", new RouteValueDictionary { 
        { "days[0]", DaysEnum.Sun }, { "days[1]", DaysEnum.Mon } 
    }) %>