没有为Json请求执行ModelBinder

本文关键字:执行 ModelBinder 请求 Json | 更新日期: 2023-09-27 17:59:31

这是我的模型活页夹

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);
}

但是,当我导航到Json的Controller/Action请求时,我的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类。它完全绕过它。

没有为Json请求执行ModelBinder

首先,我认为您应该这样注册custom BinderModelBinders.Binders.Add(typeof(DateTime), new DateTimeModelBinder());

代替ModelBinders.Binders[typeof(DateTime)] = new DateTimeModelBinder();