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>

  • 相关阅读:
    Asp.net MVC routing 路由
    Asp.net MVC3 企业网站系统高仿博客园 首页左侧列表页面 实现效果
    Asp.net MVC 3 开发简单的企业系统开篇数据库
    Asp.net MVC 3 开发企业网站系统仿照博客园部分功能总体设计
    [转]C语言中的文件格式化读写函数:fprintf和fscanf
    如何讀取/寫入文字檔? (IC Design) (Verilog)
    Verilog状态机的编写学习
    [转] verilog中的integer和reg的差别
    verilog常用系统函数以及例子
    独立写testbench注意的几点
  • 原文地址:https://www.cnblogs.com/darrenji/p/3798284.html
Copyright © 2011-2022 走看看