这是我的模型装订器
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (value == null || value.AttemptedValue == "null" || value.AttemptedValue == string.Empty)
{
return null;
}
var rawDateTimeValue = (DateTime)value.ConvertTo(typeof(DateTime));
if (!rawDateTimeValue.Equals(rawDateTimeValue.ToMinTime()))
{
return TimeZoneManager.GetUtcTime(rawDateTimeValue);
}
return rawDateTimeValue;
}
以下是我在Global.asax
中注册的方法ModelBinders.Binders[typeof(DateTime)] = new DateTimeModelBinder();
这是我的TestModel类的样子
public class TestModel
{
[JsonProperty(ItemConverterType = typeof(JavaScriptDateTimeConverter))]
public DateTime LastModified { get; set; }
[JsonProperty(ItemConverterType = typeof(JavaScriptDateTimeConverter))]
public DateTime? LastModifiedNullable { get; set; }
[JsonProperty(ItemConverterType = typeof(JavaScriptDateTimeConverter))]
public string TheStrinDateTime { get; set; }
}
当我导航到我的Controller / Action MyTest时,我可以调用我的ModelBinder类。以下作品
public ActionResult MyTest()
{
var model = new TestModel {LastModified = DateTime.UtcNow, LastModifiedNullable = DateTime.UtcNow};
return View("MyTest1", model);
}
但是当我导航到我的Controller / Action for Json请求时,我的ModelBinder类代码没有被调用。最终,我希望能够将我的Json请求日期转换为UTC日期时间。
public ActionResult MyTestJsonB()
{
var myTestModel = new TestModel
{
LastModified = DateTime.UtcNow,
LastModifiedNullable = DateTime.UtcNow,
TheStrinDateTime = "hello"
};
return Json(myTestModel, "text/plain", JsonRequestBehavior.AllowGet);
}
问题:当我调用请求MyTestJsonB时,如何调用ModelBinder类。它完全绕过它。
答案 0 :(得分:1)
首先,我认为您应该像custom Binder
ModelBinders.Binders.Add(typeof(DateTime), new DateTimeModelBinder());
而不是ModelBinders.Binders[typeof(DateTime)] = new DateTimeModelBinder();