zoukankan      html  css  js  c++  java
  • 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>

  • 相关阅读:
    C#使用Selenium实现QQ空间数据抓取 说说抓取
    C#使用Selenium实现QQ空间数据抓取 登录QQ空间
    [bug系列]Method not found: 'Void Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommandBuilderFactory
    【原创】CA证书申请+IIS配置HTTPS+默认访问https路径
    【原创】MVC项目中使用JQuery的upladify图片上传插件相关问题的解决方案
    Jquery中$.ajax()方法参数详解
    开发IOS应用真的一定要买苹果电脑设备吗?
    vim全选内容命令
    配置jdk环境变量
    mysql联查中使用if和group by会让你的结果不是你想要的
  • 原文地址:https://www.cnblogs.com/darrenji/p/3798284.html
Copyright © 2011-2022 走看看