MVC擴充ModelBinder使類型為DateTime的Action參數可以接收日期格式的字串

來源:互聯網
上載者:User

標籤: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>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.