在Asp.net MVC自定义DateTime模型联 [英] Custom DateTime model binder in Asp.net MVC

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

问题描述

我想写出的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

我的模型具有如上看到一个属性(出生)。因此,当模型试图请求数据绑定到这个属性,我的模型绑定的 BindModel(controllerContext,BindingContext中)被调用。一切OK,但。 如何才能获得财产控制器/ BindingContext中的属性,要正确解析我的约会?我怎样才能到 PropertyDesciptor 的属性出生

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总成装配定义。设置自定义绑定(类似<一个href=\"http://www.hanselman.com/blog/SplittingDateTimeUnitTestingASPNETMVCCustomModelBinders.aspx\">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自定义DateTime模型联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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