【问题标题】:ModelBinder not being executed for Json Request没有为 Json 请求执行 ModelBinder
【发布时间】:2014-04-23 18:32:02
【问题描述】:

这是我的模型活页夹

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 请求的控制器/操作时,我的 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类。它完全绕过它。

【问题讨论】:

    标签: c# json asp.net-mvc-4


    【解决方案1】:

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

    而不是ModelBinders.Binders[typeof(DateTime)] = new DateTimeModelBinder();

    【讨论】:

      猜你喜欢
      • 2014-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多