標籤:style blog http color 使用 width
原文:MVC擴充ModelBinder使類型為DateTime的Action參數可以接收日期格式的字串
如何讓視圖通過某種途徑,把符合日期格式的字串放到路由中,再傳遞給類型為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>