ASP.NET MVC将ActionLink中的DateTime数组/集合从View传递到Controller

时间:2013-09-27 16:01:12

标签: c# asp.net asp.net-mvc asp.net-mvc-4

我正在尝试从我的视图中传递DateTime的集合:

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

这是我的行动:

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

但我总是在约会中得到零。有什么建议吗?

更新

问题是因为我认为它会创建错误的网址:

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

顺便说一句,我补充说:

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

采取行动:

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

1 个答案:

答案 0 :(得分:1)

很抱歉,我不知道如何使用UrlActionLink或Url.Action,因为它们会对括号进行编码,但如果您传递正确的查询字符串,默认的ModelBinder可以处理ICollection日期,如下所示

    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>

网址将如下/ Home / Index?dates [0] = 2012-11-12T00:00:00&amp; dates [1] = 2013-09-13T00:00:00

相关问题