如何讓視圖通過某種途徑,把符合日期格式的字符串放到路由中,再傳遞給類型為DateTime的控制器方法參數?即string→DateTime。MVC默認的ModelBinder并沒有提供這樣的機制,所以我們要自定義一個ModelBinder。
首先,在前臺視圖中,把符合日期格式的字符串賦值給date變量放在路由中:
@Html.ActionLink("傳入日期格式為2014-06-19","Date",new {date = "2014-06-19"})
控制器方法中,希望這樣接收date這個變量:
public ActionResult Date(DateTime date)
{
ViewData["Date"] = date;
return View();
}
自定義的ModelBinder實現IModelBinder接口:
using System;
using System.Web.Mvc;
namespace MvcApplication1.Extension
{
public class DateTimeModelBinder : IModelBinder
{
public string Format { get; private set; }
public DateTimeModelBinder(string format)
{
this.Format = format;
}
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
//從ValueProvider中,模型名稱為key,獲取該模型的值
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
return DateTime.ParseExact((string)value.AttemptedValue, this.Format, null);
}
}
}
以上,通過構造函數注入格式,通過屬性使用格式,在BindModel()方法中取出ValueProvider中的值,再轉換成DateTime類型。
接下來的問題是:DateTime date如何才能用上自定義的ModelBinder呢?為此,我們需要一個派生于CustomModelBinderAttribute的類,重寫CustomModelBinderAttribute的GetBinder()方法。
using System.Web.Mvc;
namespace MvcApplication1.Extension
{
public class DateTimeAttribute : CustomModelBinderAttribute
{
public string Format { get; private set; }
public DateTimeAttribute(string format)
{
this.Format = format;
}
public override IModelBinder GetBinder()
{
return new DateTimeModelBinder(this.Format);
}
}
}
再把DateTimeAttribute打到控制器方法參數上:
public ActionResult Date([DateTime("yyyy-MM-dd")]DateTime date)
{
ViewData["Date"] = date;
return View();
}
于是,最終可以在視圖中這樣使用從控制器方法傳來的、放在ViewData中DateTime類型:
@{
var date = (DateTime) ViewData["Date"];
}
<span>接收到的日期是:</span>
<span>@date.ToShortDateString()</span>