gpt4 book ai didi

asp.net-mvc - Asp.net MVC 中的自定义 DateTime 模型绑定(bind)器

转载 作者:行者123 更新时间:2023-12-03 11:03:20 27 4
gpt4 key购买 nike

我想为 DateTime 编写自己的模型活页夹类型。首先,我想编写一个可以附加到模型属性的新属性,例如:

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

这是简单的部分。但是活页夹部分要困难一些。我想为类型 DateTime 添加一个新的模型绑定(bind)器.我可以
  • 实现IModelBinder接口(interface)并自己编写BindModel()方法
  • 继承自 DefaultModelBinder并覆盖 BindModel()方法

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

    编辑

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

    最佳答案

    您可以使用 IModelBinder 更改默认模型绑定(bind)器以使用用户文化

    public class DateTimeBinder : IModelBinder
    {
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
    var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
    bindingContext.ModelState.SetModelValue(bindingContext.ModelName, value);

    return value.ConvertTo(typeof(DateTime), CultureInfo.CurrentCulture);
    }
    }

    public class NullableDateTimeBinder : IModelBinder
    {
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
    var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
    bindingContext.ModelState.SetModelValue(bindingContext.ModelName, value);

    return value == null
    ? null
    : value.ConvertTo(typeof(DateTime), CultureInfo.CurrentCulture);
    }
    }

    在 Global.Asax 中将以下内容添加到 Application_Start() 中:
    ModelBinders.Binders.Add(typeof(DateTime), new DateTimeBinder());
    ModelBinders.Binders.Add(typeof(DateTime?), new NullableDateTimeBinder());

    阅读更多 this excellent blog这描述了为什么 Mvc 框架团队为所有用户实现了默认文化。

    关于asp.net-mvc - Asp.net MVC 中的自定义 DateTime 模型绑定(bind)器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2356601/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com