Asp.net MVC 中的自定义日期时间模型绑定器 [英] Custom DateTime model binder in Asp.net MVC

查看:39
本文介绍了Asp.net MVC 中的自定义日期时间模型绑定器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为 DateTime 类型编写我自己的模型绑定器.首先,我想编写一个可以附加到我的模型属性的新属性,例如:

I would like to write my own model binder for DateTime type. First of all I'd like to write a new attribute that I can attach to my model property like:

[DateTimeFormat("d.M.yyyy")]
public DateTime Birth { get; set,}

这是简单的部分.但是活页夹部分有点困难.我想为 DateTime 类型添加一个新的模型绑定器.我也可以

This is the easy part. But the binder part is a bit more difficult. I would like to add a new model binder for type DateTime. I can either

  • 实现IModelBinder接口并编写自己的BindModel()方法
  • DefaultModelBinder继承并覆盖BindModel()方法
  • implement IModelBinder interface and write my own BindModel() method
  • inherit from DefaultModelBinder and override BindModel() method

我的模型有一个如上所示的属性(Birth).因此,当模型尝试将请求数据绑定到此属性时,我的模型绑定器的 BindModel(controllerContext, bindingContext) 被调用.一切正常,但是.如何从控制器/bindingContext 获取属性属性,以正确解析我的日期?我怎样才能到达Birth 属性的PropertyDescriptor?

My model has a property as seen above (Birth). So when the model tries to bind request data to this property, my model binder's BindModel(controllerContext, bindingContext) gets invoked. Everything ok, but. How do I get property attributes from controller/bindingContext, to parse my date correctly? How can I get to the PropertyDesciptor of property Birth?

由于关注点分离,我的模型类定义在一个不(也不应该)引用 System.Web.MVC 程序集的程序集中.在这里设置自定义绑定(类似于 Scott Hanselman 的示例)属性是不可行的.

Because of separation of concerns my model class is defined in an assembly that doesn't (and shouldn't) reference System.Web.MVC assembly. Setting custom binding (similar to Scott Hanselman's example) attributes is a no-go here.

推荐答案

我认为您不应该在模型上放置特定于区域设置的属性.

I don't think you should put locale-specific attributes on a model.

此问题的其他两种可能解决方案是:

Two other possible solutions to this problem are:

  • 让您的页面将日期从语言环境特定格式音译为通用格式,例如 JavaScript 中的 yyyy-mm-dd.(有效,但需要 JavaScript.)
  • 编写一个模型绑定器,在解析日期时考虑当前的 UI 文化.

要回答您的实际问题,获取自定义属性(对于 MVC 2)的方法是 编写 AssociatedMetadataProvider.

To answer your actual question, the way to get custom attributes (for MVC 2) is to write an AssociatedMetadataProvider.

这篇关于Asp.net MVC 中的自定义日期时间模型绑定器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆