0

I'm trying to pass Collection of DateTime from my View:

@Html.ActionLink("Hello", "Index", "Home", new { dates = new Collection(){date1, date2)} })

Here is my action:

[HttpGet]
public ActionResult Index(int? page, string searchString, ICollection<DateTime> dates)
{ ...

But i always get null in dates. Any suggestions?

Update

The problem is as i think it creates incorrect url:

http://localhost:39152/Home?dates=System.Collections.ObjectModel.Collection%601%5BSystem.DateTime%5D

Btw i added:

public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
  var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
  var date = value.ConvertTo(typeof (DateTime), CultureInfo.CurrentCulture);
  return date;
}

And to action:

[HttpGet]
public ActionResult Index(int? page, string searchString, [ModelBinder(typeof (ModelBinders.DateTimeBinder))]  ICollection<DateTime> dates)
{ ...

1 Answers1

1

Sorry, I don't know how to do it with UrlActionLink or Url.Action because they will encode the bracket, but the default ModelBinder can handle ICollection dates if you pass the correct query string, something like this

    var dates = new[] { new DateTime(2012, 11, 12), new DateTime(2013, 09, 13) };
    <a href="@(Url.Action("Index", "Home"))?@(string.Join("&", dates.Select((date, i) => Url.Encode("dates") + "[" + i + "]=" + date.ToString("s"))))">Hello</a>

The url will look like this /Home/Index?dates[0]=2012-11-12T00:00:00&dates[1]=2013-09-13T00:00:00

teamchong
  • 1,326
  • 3
  • 16
  • 13