MVC扩展ModelBinder使类型为DateTime的Action参数可以接收日期格式的字符串

原文: 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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值