Asp.net-Mvc
Asp.net MVC 中的自定義 DateTime 模型綁定器
我想為
DateTime類型編寫自己的模型活頁夾。首先,我想編寫一個可以附加到模型屬性的新屬性,例如:[DateTimeFormat("d.M.yyyy")] public DateTime Birth { get; set,}這是簡單的部分。但是活頁夾部分要困難一些。我想為 type 添加一個新的模型綁定器
DateTime。我可以
- 實現
IModelBinder介面並編寫自己的BindModel()方法- 繼承
DefaultModelBinder和覆蓋BindModel()方法我的模型具有如上所示的屬性 (
Birth)。因此,當模型嘗試將請求數據綁定到此屬性時,我的模型綁定器BindModel(controllerContext, bindingContext)會被呼叫。一切都好,但是。如何從控制器/bindingContext 獲取屬性屬性,以正確解析我的日期?我怎樣才能到達PropertyDesciptor物業Birth?編輯
由於關注點分離,我的模型類是在不(也不應該)引用 System.Web.MVC 程序集的程序集中定義的。設置自定義綁定(類似於Scott Hanselman 的範例)屬性在這裡是不行的。
我認為您不應該將特定於語言環境的屬性放在模型上。
這個問題的另外兩個可能的解決方案是:
- 讓您的頁面將日期從特定於語言環境的格式音譯為通用格式,例如 JavaScript 中的 yyyy-mm-dd。(有效,但需要 JavaScript。)
- 編寫一個模型綁定器,在解析日期時考慮目前的 UI 文化。
要回答您的實際問題,獲取自定義屬性(對於 MVC 2)的方法是編寫一個 AssociatedMetadataProvider。
您可以使用 IModelBinder 更改預設模型綁定器以使用使用者文化
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());在這個優秀的部落格上閱讀更多內容,該部落格描述了為什麼 Mvc 框架團隊為所有使用者實現了預設文化。