您的位置:首页 > 其它

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

2014-06-28 13:35 411 查看
原文:MVC扩展ModelBinder使类型为DateTime的Action参数可以接收日期格式的字符串如何让视图通过某种途径,把符合日期格式的字符串放到路由中,再传递给类型为DateTime的控制器方法参数?即string→DateTime。MVC默认的ModelBinder并没有提供这样的机制,所以我们要自定义一个ModelBinder。

首先,在前台视图中,把符合日期格式的字符串赋值给date变量放在路由中:
@Html.ActionLink("传入日期格式为2014-06-19","Date",new {date = "2014-06-19"})

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

控制器方法中,希望这样接收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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐